summaryrefslogtreecommitdiff
path: root/src/cups/backend_dnpds40.c
blob: b9ed3e46f1a74861d5f9ab073c27fc8b2eb69055 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
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
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
/*
 *   Citizen / DNP Photo Printer CUPS backend -- libusb-1.0 version
 *
 *   (c) 2013-2018 Solomon Peachy <pizza@shaftnet.org>
 *
 *   Development of this backend was sponsored by:
 *
 *     Marco Di Antonio and [ ilgruppodigitale.com ]
 *     LiveLink Technology [ www.livelinktechnology.net ]
 *     A generous benefactor who wishes to remain anonymous
 *
 *   The latest version of this program can be found at:
 *
 *     http://git.shaftnet.org/cgit/selphy_print.git
 *
 *   This program is free software; you can redistribute it and/or modify it
 *   under the terms of the GNU General Public License as published by the Free
 *   Software Foundation; either version 2 of the License, or (at your option)
 *   any later version.
 *
 *   This program is distributed in the hope that it will be useful, but
 *   WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 *   or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 *   for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 *          [http://www.gnu.org/licenses/gpl-2.0.html]
 *
 *   SPDX-License-Identifier: GPL-2.0+
 *
 */

//#define DNP_ONLY
//#define CITIZEN_ONLY

/* Enables caching of last print type to speed up
   job pipelining.  Without this we always have to
   assume the worst */
//#define STATE_DIR "/tmp"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>

#define BACKEND dnpds40_backend

#include "backend_common.h"

/* Private data structure */
struct dnpds40_printjob {
	uint8_t *databuf;
	int datalen;

	int copies;
	uint32_t dpi;
	int matte;
	int cutter;
	uint32_t multicut;
	int fullcut;
	int printspeed;
	int can_rewind;
	int buf_needed;
};

struct dnpds40_ctx {
	struct libusb_device_handle *dev;
	uint8_t endp_up;
	uint8_t endp_down;

	int type;

	/* Version and whatnot */
	char *serno;
	char *version;
	int ver_major;
	int ver_minor;

	/* State */
	uint32_t media;
	uint32_t duplex_media;
	uint16_t media_count_new;

	uint32_t last_multicut;
	int last_matte;

	int mediaoffset;
	int correct_count;
	int needs_mlot;

	struct marker marker;

	/* Printer capabilities */
	uint32_t native_width;
	uint32_t max_height;
	int supports_6x9;
	int supports_2x6;
	int supports_3x5x2;
	int supports_matte;
	int supports_finematte;
	int supports_luster;
	int supports_advmatte;
	int supports_fullcut;
	int supports_rewind;
	int supports_standby;
	int supports_6x4_5;
	int supports_mqty_default;
	int supports_iserial;
	int supports_6x6;
	int supports_5x5;
	int supports_counterp;
	int supports_adv_fullcut;
	int supports_mediaoffset;
	int supports_media_ext;
	int supports_printspeed;
	int supports_lowspeed;
	int supports_highdensity;
	int supports_gamma;
};

struct dnpds40_cmd {
	uint8_t esc; /* Fixed at ascii ESC, aka 0x1B */
	uint8_t p;   /* Fixed at ascii 'P' aka 0x50 */
	uint8_t arg1[6];
	uint8_t arg2[16];
	uint8_t arg3[8]; /* Decimal value of arg4's length, or empty */
	uint8_t arg4[0]; /* Extra payload if arg3 is non-empty
			    Doesn't have to be sent in the same URB */

	/* All unused elements are set to 0x20 (ie ascii space) */
};

#define MULTICUT_5x3_5     1
#define MULTICUT_6x4       2
#define MULTICUT_5x7       3
#define MULTICUT_6x8       4
#define MULTICUT_6x9       5
#define MULTICUT_8x10      6
#define MULTICUT_8x12      7
#define MULTICUT_8x4       8
#define MULTICUT_8x5       9
#define MULTICUT_8x6      10
#define MULTICUT_8x8      11
#define MULTICUT_6x4X2    12
#define MULTICUT_8x4X2    13
#define MULTICUT_8x5X2    14
#define MULTICUT_8x6X2    15
#define MULTICUT_8x5_8x4  16
#define MULTICUT_8x6_8x4  17
#define MULTICUT_8x6_8x5  18
#define MULTICUT_8x8_8x4  19
#define MULTICUT_8x4X3    20
#define MULTICUT_8xA4LEN  21
#define MULTICUT_5x3_5X2  22
#define MULTICUT_6x6      27
#define MULTICUT_5x5      29
#define MULTICUT_6x4_5    30
#define MULTICUT_6x4_5X2  31
#define MULTICUT_8x7      32
#define MULTICUT_8x9      33
#define MULTICUT_A5       34
#define MULTICUT_A5X2     35
#define MULTICUT_A4x4     36
#define MULTICUT_A4x5     37
#define MULTICUT_A4x6     38
#define MULTICUT_A4x8     39
#define MULTICUT_A4x10    40
#define MULTICUT_A4       41
#define MULTICUT_A4x5X2   43


#define MULTICUT_S_SIMPLEX  100
#define MULTICUT_S_FRONT    200
#define MULTICUT_S_BACK     300

#define MULTICUT_S_8x10     6
#define MULTICUT_S_8x12     7
#define MULTICUT_S_8x4      8
#define MULTICUT_S_8x5      9
#define MULTICUT_S_8x6     10
#define MULTICUT_S_8x8     11
#define MULTICUT_S_8x4X2   13
#define MULTICUT_S_8x5X2   14
#define MULTICUT_S_8x6X2   15
#define MULTICUT_S_8x10_5  25
#define MULTICUT_S_8x10_75 26
#define MULTICUT_S_8x4X3   28  // different than roll type.

#define min(__x, __y) ((__x) < (__y)) ? __x : __y

/* Legacy CW-01 spool file support */
struct cw01_spool_hdr {
	uint8_t  type; /* 0x00 -> 0x06 */
	uint8_t  res; /* vertical resolution; 0x00 == 334dpi, 0x01 == 600dpi */
	uint8_t  copies; /* number of prints */
	uint8_t  null0;
	uint32_t plane_len; /* LE */
	uint8_t  null1[4];
};

#define DPI_334 0
#define DPI_600 1

#define TYPE_DSC  0
#define TYPE_L    1
#define TYPE_PC   2
#define TYPE_2DSC 3
#define TYPE_3L   4
#define TYPE_A5   5
#define TYPE_A6   6
/* Legacy CW-01 spool file support */

static int cw01_read_parse(struct dnpds40_printjob *job, int data_fd,
			   struct cw01_spool_hdr *hdr, int read_data);
static void dnpds40_cleanup_job(const void *vjob);

#define JOB_EQUIV(__x)  if (job1->__x != job2->__x) goto done

static struct dnpds40_printjob *combine_jobs(const struct dnpds40_printjob *job1,
					     const struct dnpds40_printjob *job2)
{
	struct dnpds40_printjob *newjob = NULL;
	uint32_t new_multicut;
	uint16_t new_w, new_h;
	uint16_t gap_bytes;

	/* Sanity check */
	if (!job1 || !job2)
		goto done;

	/* Make sure pertinent paremeters are the same */
	JOB_EQUIV(dpi);
	JOB_EQUIV(matte);
	JOB_EQUIV(cutter);
	JOB_EQUIV(fullcut);
	JOB_EQUIV(multicut);  // TODO:  Support fancier modes for 8" models (eg 8x4+8x6, etc)
	JOB_EQUIV(datalen); // <-- cheating a little?
	// JOV_EQUIV(printspeed); <-- does it matter?

	/* Any cutter means we shouldn't bother */
	if (job1->fullcut || job1->cutter)
		goto done;

#if 0
	// XXX TODO:  2x6*2 + 2x6*2 --> 8x6+cutter!
	// problem is that 8x6" size is 4 rows smaller than 2* 4x6" prints, posing a problem.

	/* Only handle cutter if it's for 2x6" strips */
	if (job1->cutter != 0 && job1->cutter != 120)
		goto done;
#endif

	/* Make sure we can combine these two prints */
	switch (job1->multicut) {
	case MULTICUT_5x3_5:
		new_multicut = MULTICUT_5x3_5X2;
		new_w = 1920;
		new_h = 2176;
		gap_bytes = 0;
		break;
	case MULTICUT_6x4:
#if 0
		if (job1->cutter != 120) {
			new_multicut = MULTICUT_6x8;
			new_h = 2436;
			gap_bytes = -4;
		} else {
#endif
			new_multicut = MULTICUT_6x4X2;
			new_h = 2498;
			gap_bytes = 18;
#if 0
		}
#endif
		new_w = 1920;
		break;
	case MULTICUT_6x4_5:
		new_multicut = MULTICUT_6x4_5X2;
		new_w = 1920;
		new_h = 2802;
		gap_bytes = 30;
		break;
	case MULTICUT_8x4:
		new_multicut = MULTICUT_8x4X2;
		new_w = 2560;
		new_h = 2502;
		gap_bytes = 30;
		break;
	case MULTICUT_8x5:
		new_multicut = MULTICUT_8x5X2;
		new_w = 2560;
		new_h = 3102;
		gap_bytes = 30;
		break;
	case MULTICUT_8x6:
		new_multicut = MULTICUT_8x6X2;
		new_w = 2560;
		new_h = 3702;
		gap_bytes = 30;
		break;
	default:
		// 2-up 8x6 prints too?
		/* Everything else is NOT handled */
		goto done;
	}
	gap_bytes *= new_w;
	if (job1->dpi == 600) {
		gap_bytes *= 2;
		new_h *= 2;
	}

	DEBUG("Combining jobs to save media\n");

	/* Okay, it's kosher to proceed */

	newjob = malloc(sizeof(*newjob));
	if (!newjob) {
		ERROR("Memory allocation failure!\n");
		goto done;
	}
	memcpy(newjob, job1, sizeof(*newjob));

	newjob->databuf = malloc(((new_w*new_h+1024+54+10))*3+1024);
	newjob->datalen = 0;
	newjob->multicut = new_multicut;
	if (!newjob->databuf) {
		dnpds40_cleanup_job(newjob);
		newjob = NULL;
		ERROR("Memory allocation failure!\n");
		goto done;
	}

	/* Copy data blocks from job1 */
	uint8_t *ptr, *ptr2;
	char buf[9];
	ptr = job1->databuf;
	while(ptr && ptr < (job1->databuf + job1->datalen)) {
		int i;
		buf[8] = 0;
		memcpy(buf, ptr + 24, 8);
		i = atoi(buf) + 32;
		memcpy(newjob->databuf + newjob->datalen, ptr, i);

		/* If we're on a plane data block... */
		if (!memcmp("PLANE", newjob->databuf + newjob->datalen + 9, 5)) {
			long planelen = (new_w * new_h) + 1088;
			uint32_t newlen;

			/* Fix up length in command */
			snprintf(buf, sizeof(buf), "%08ld", planelen);
			memcpy(newjob->databuf + newjob->datalen + 24, buf, 8);

			/* Alter BMP header */
			newlen = cpu_to_le32(planelen);
			memcpy(newjob->databuf + newjob->datalen + 32 + 2, &newlen, 4);

			/* alter DIB header */
			newlen = cpu_to_le32(new_h);
			memcpy(newjob->databuf + newjob->datalen + 32 + 22, &newlen, 4);

			/* Insert gap/padding after first image */
			memset(newjob->databuf + newjob->datalen + i, 0, gap_bytes);
			newjob->datalen += gap_bytes;

			// locate job2's PLANE properly?  Assumption is it's in the same place.
			ptr2 = job2->databuf + (ptr - job1->databuf);
			/* Copy over job2's image data */
			memcpy(newjob->databuf + newjob->datalen + i,
			        ptr2 + 32 + 1088, i - 32 - 1088);
			newjob->datalen += i - 32 - 1088;  /* add in job2 length */
		}

		newjob->datalen += i;
		ptr += i;
	}

done:
	return newjob;
}

#undef JOB_EQUIV

static void dnpds40_build_cmd(struct dnpds40_cmd *cmd, char *arg1, char *arg2, uint32_t arg3_len)
{
	memset(cmd, 0x20, sizeof(*cmd));
	cmd->esc = 0x1b;
	cmd->p = 0x50;
	memcpy(cmd->arg1, arg1, min(strlen(arg1), sizeof(cmd->arg1)));
	memcpy(cmd->arg2, arg2, min(strlen(arg2), sizeof(cmd->arg2)));
	if (arg3_len) {
		char buf[9];
		snprintf(buf, sizeof(buf), "%08u", arg3_len);
		memcpy(cmd->arg3, buf, 8);
	}

}

static void dnpds40_cleanup_string(char *start, int len)
{
	char *ptr = strchr(start, 0x0d);

	if (ptr && (ptr - start < len)) {
		*ptr = 0x00; /* If there is a <CR>, terminate there */
		len = ptr - start;
	} else {
		start[--len] = 0x00;  /* force null-termination */
	}

	/* Trim trailing spaces */
	while (len && start[len-1] == ' ') {
		start[--len] = 0;
	}
}

static char *dnpds40_printer_type(int type)
{
	switch(type) {
	case P_DNP_DS40: return "DS40";
	case P_DNP_DS80: return "DS80";
	case P_DNP_DS80D: return "DS80DX";
	case P_DNP_DSRX1: return "DSRX1";
	case P_DNP_DS620: return "DS620";
	case P_DNP_DS820: return "DS820";
	case P_CITIZEN_CW01: return "CW01";
	case P_CITIZEN_OP900II: return "OP900ii";
	default: break;
	}
	return "Unknown";
}

static char *dnpds40_media_types(int media)
{
	switch (media) {
	case 100: return "UNKNOWN100"; // seen in driver dumps
	case 110: return "UNKNOWN110"; // seen in driver dumps
	case 200: return "5x3.5 (L)";
	case 210: return "5x7 (2L)";
	case 300: return "6x4 (PC)";
	case 310: return "6x8 (A5)";
	case 400: return "6x9 (A5W)";
	case 500: return "8x10";
	case 510: return "8x12";
	case 600: return "A4";
	default:
		break;
	}

	return "Unknown type";
}

static char *dnpds620_media_extension_code(int media)
{
	switch (media) {
	case 00: return "Normal Paper";
	case 01: return "Sticky Paper";
	case 99: return "Unknown Paper";
	default:
		break;
	}

	return "Unknown type";
}

static char *dnpds820_media_subtypes(int media)
{
	switch (media) {
	case 0001: return "SD";
	case 0003: return "PP";
	default:
		break;
	}

	return "Unknown type";
}

static char *dnpds80_duplex_media_types(int media)
{
	switch (media) {
	case 100: return "8x10.75";
	case 200: return "8x12";
	default:
		break;
	}

	return "Unknown type";
}

static char *dnpds80_duplex_statuses(int status)
{
	switch (status) {
	case 5000: return "No Error";

	case 5500: return "Duplex Unit Not Connected";

	case 5017: return "Paper Jam: Supply Sensor On";
	case 5018: return "Paper Jam: Supply Sensor Off";
	case 5019: return "Paper Jam: Slot Sensor On";
	case 5020: return "Paper Jam: Slot Sensor Off";
	case 5021: return "Paper Jam: Pass Sensor On";
	case 5022: return "Paper Jam: Pass Sensor Off";
	case 5023: return "Paper Jam: Shell Sensor 1 On";
	case 5024: return "Paper Jam: Shell Sensor 1 Off";
	case 5025: return "Paper Jam: Shell Sensor 2 On";
	case 5026: return "Paper Jam: Shell Sensor 2 Off";
	case 5027: return "Paper Jam: Eject Sensor On";
	case 5028: return "Paper Jam: Eject Sensor Off";
	case 5029: return "Paper Jam: Slot FG Sensor";
	case 5030: return "Paper Jam: Shell FG Sensor";

	case 5033: return "Paper Supply Sensor Off";
	case 5034: return "Printer Feed Slot Sensor Off";
	case 5035: return "Pinch Pass Sensor Off";
	case 5036: return "Shell Pass Sensor 1 Off";
	case 5037: return "Shell Pass Sensor 2 Off";
	case 5038: return "Eject Sensor Off";

	case 5049: return "Capstan Drive Control Error";
	case 5065: return "Shell Roller Error";

	case 5081: return "Pinch Open Error";
	case 5082: return "Pinch Close Error";
	case 5083: return "Pinch Init Error";
	case 5084: return "Pinch Position Error";

	case 5097: return "Pass Guide Supply Error";
	case 5098: return "Pass Guide Shell Error";
	case 5099: return "Pass Guide Eject Error";
	case 5100: return "Pass Guide Init Error";
	case 5101: return "Pass Guide Position Error";

	case 5113: return "Side Guide Home Error";
	case 5114: return "Side Guide Position Error";
	case 5115: return "Side Guide Init Error";

	case 5129: return "Act Guide Home Error";

	case 5145: return "Shell Rotate Home Error";
	case 5146: return "Shell Rotate Rev Error";

	case 5161: return "Paper Feed Lever Down Error";
	case 5162: return "Paper Feed Lever Lock Error";
	case 5163: return "Paper Feed Lever Up Error";

	case 5177: return "Cutter Home Error";
	case 5178: return "Cutter Away Error";
	case 5179: return "Cutter Init Error";
	case 5180: return "Cutter Position Error";

	case 5193: return "Paper Tray Removed";
	case 5209: return "Cover Opened";
	case 5241: return "System Error";

	default:
		break;
	}

	return "Unknown Duplexer Error";
}

static char *dnpds40_statuses(int status)
{
	if (status >= 5000 && status <= 5999)
		return dnpds80_duplex_statuses(status);

	switch (status) {
	case 0:	return "Idle";
	case 1:	return "Printing";
	case 500: return "Cooling Print Head";
	case 510: return "Cooling Paper Motor";
	case 900: return "Standby Mode";
	case 1000: return "Cover Open";
	case 1010: return "No Scrap Box";
	case 1100: return "Paper End";
	case 1200: return "Ribbon End";
	case 1300: return "Paper Jam";
	case 1400: return "Ribbon Error";
	case 1500: return "Paper Definition Error";
	case 1600: return "Data Error";
	case 2000: return "Head Voltage Error";
	case 2100: return "Head Position Error";
	case 2200: return "Power Supply Fan Error";
	case 2300: return "Cutter Error";
	case 2400: return "Pinch Roller Error";
	case 2500: return "Abnormal Head Temperature";
	case 2600: return "Abnormal Media Temperature";
	case 2610: return "Abnormal Paper Motor Temperature";
	case 2700: return "Ribbon Tension Error";
	case 2800: return "RF-ID Module Error";
	case 3000: return "System Error";
	default:
		break;
	}

	return "Unknown Error";
}

static int dnpds40_do_cmd(struct dnpds40_ctx *ctx,
			  struct dnpds40_cmd *cmd,
			  uint8_t *data, int len)
{
	int ret;

	if ((ret = send_data(ctx->dev, ctx->endp_down,
			     (uint8_t*)cmd, sizeof(*cmd))))
		return ret;

	if (data && len)
		if ((ret = send_data(ctx->dev, ctx->endp_down,
				     data, len)))
			return ret;

	return CUPS_BACKEND_OK;
}

static uint8_t *dnpds40_resp_cmd2(struct dnpds40_ctx *ctx,
				  struct dnpds40_cmd *cmd,
				  int *len,
				  uint8_t *buf, uint32_t buf_len)
{
	char tmp[9];
	uint8_t *respbuf;

	int ret, i, num = 0;

	memset(tmp, 0, sizeof(tmp));

	if ((ret = dnpds40_do_cmd(ctx, cmd, buf, buf_len)))
		return NULL;

	/* Read in the response header */
	ret = read_data(ctx->dev, ctx->endp_up,
			(uint8_t*)tmp, 8, &num);
	if (ret < 0)
		return NULL;

	if (num != 8) {
		ERROR("Short read! (%d/%d)\n", num, 8);
		return NULL;
	}

	i = atoi(tmp);  /* Length of payload in bytes, possibly padded */
	respbuf = malloc(i);
	if (!respbuf) {
		ERROR("Memory allocation failure (%d bytes)!\n", i);
		return NULL;
	}

	/* Read in the actual response */
	ret = read_data(ctx->dev, ctx->endp_up,
			respbuf, i, &num);
	if (ret < 0) {
		free(respbuf);
		return NULL;
	}

	if (num != i) {
		ERROR("Short read! (%d/%d)\n", num, i);
		free(respbuf);
		return NULL;
	}

	*len = num;
	return respbuf;
}

#define dnpds40_resp_cmd(__ctx, __cmd, __len) dnpds40_resp_cmd2(__ctx, __cmd, __len, NULL, 0)

static int dnpds40_query_serno(struct libusb_device_handle *dev, uint8_t endp_up, uint8_t endp_down, char *buf, int buf_len)
{
	struct dnpds40_cmd cmd;
	uint8_t *resp;
	int len = 0;

	struct dnpds40_ctx ctx = {
		.dev = dev,
		.endp_up = endp_up,
		.endp_down = endp_down,
	};

	/* Get Serial Number */
	dnpds40_build_cmd(&cmd, "INFO", "SERIAL_NUMBER", 0);

	resp = dnpds40_resp_cmd(&ctx, &cmd, &len);
	if (!resp)
		return CUPS_BACKEND_FAILED;

	dnpds40_cleanup_string((char*)resp, len);

	strncpy(buf, (char*)resp, buf_len);
	buf[buf_len-1] = 0;

	free(resp);

	return CUPS_BACKEND_OK;
}

static void *dnpds40_init(void)
{
	struct dnpds40_ctx *ctx = malloc(sizeof(struct dnpds40_ctx));
	if (!ctx) {
		ERROR("Memory allocation failure (%d bytes)!\n", (int)sizeof(struct dnpds40_ctx));
		return NULL;
	}
	memset(ctx, 0, sizeof(struct dnpds40_ctx));

	return ctx;
}

#define FW_VER_CHECK(__major, __minor) \
	((ctx->ver_major > (__major)) || \
	 (ctx->ver_major == (__major) && ctx->ver_minor >= (__minor)))

static int dnpds40_query_mqty(struct dnpds40_ctx *ctx)
{
	struct dnpds40_cmd cmd;
	uint8_t *resp;
	int len = 0, count;

	/* Get Media remaining */
	dnpds40_build_cmd(&cmd, "INFO", "MQTY", 0);

	resp = dnpds40_resp_cmd(ctx, &cmd, &len);
	if (!resp)
		return -1;

	dnpds40_cleanup_string((char*)resp, len);

	count = atoi((char*)resp+4);
	free(resp);

	if (count) {
		/* Old-sk00l models report one less than they should */
		if (!ctx->correct_count)
			count++;

		count -= ctx->mediaoffset;
	}

	return count;
}

static int dnpds40_attach(void *vctx, struct libusb_device_handle *dev, int type,
			  uint8_t endp_up, uint8_t endp_down, uint8_t jobid)
{
	struct dnpds40_ctx *ctx = vctx;

	UNUSED(jobid);

	ctx->dev = dev;
	ctx->endp_up = endp_up;
	ctx->endp_down = endp_down;
	ctx->type = type;

	if (test_mode < TEST_MODE_NOATTACH) {
		struct dnpds40_cmd cmd;
		uint8_t *resp;
		int len = 0;

		/* Get Firmware Version */
		dnpds40_build_cmd(&cmd, "INFO", "FVER", 0);

		resp = dnpds40_resp_cmd(ctx, &cmd, &len);
		if (resp) {
			char *ptr;
			dnpds40_cleanup_string((char*)resp, len);
			ctx->version = strdup((char*) resp);

			/* Parse version */
			/* ptr = */ strtok((char*)resp, " .");
			ptr = strtok(NULL, ".");
			ctx->ver_major = atoi(ptr);
			ptr = strtok(NULL, ".");
			ctx->ver_minor = atoi(ptr);
			free(resp);
		} else {
			return CUPS_BACKEND_FAILED;
		}

		/* Get Serial Number */
		dnpds40_build_cmd(&cmd, "INFO", "SERIAL_NUMBER", 0);

		resp = dnpds40_resp_cmd(ctx, &cmd, &len);
		if (resp) {
			dnpds40_cleanup_string((char*)resp, len);
			ctx->serno = (char*) resp;
			/* Do NOT free resp! */
		} else {
			return CUPS_BACKEND_FAILED;
		}

		/* Query Media Info */
		dnpds40_build_cmd(&cmd, "INFO", "MEDIA", 0);

		resp = dnpds40_resp_cmd(ctx, &cmd, &len);
		if (resp) {
			char tmp[4];

			dnpds40_cleanup_string((char*)resp, len);

			memcpy(tmp, resp + 4, 3);
			tmp[3] = 0;

			ctx->media = atoi(tmp);

			/* Subtract out the "mark" type */
			if (ctx->media & 1)
				ctx->media--;

			free(resp);
		} else {
			return CUPS_BACKEND_FAILED;
		}

		if (ctx->type == P_DNP_DS80D) {
			struct dnpds40_cmd cmd;
			uint8_t *resp;
			int len = 0;

			/* Query Duplex Media Info */
			dnpds40_build_cmd(&cmd, "INFO", "CUT_PAPER", 0);

			resp = dnpds40_resp_cmd(ctx, &cmd, &len);
			if (resp) {
				char tmp[5];

				dnpds40_cleanup_string((char*)resp, len);

				memcpy(tmp, resp + 4, 4);
				tmp[4] = 0;

				ctx->duplex_media = atoi(tmp);

				/* Subtract out the paper status */
				if (ctx->duplex_media & 3)
					ctx->duplex_media -= (ctx->duplex_media & 3);

				free(resp);
			} else {
				return CUPS_BACKEND_FAILED;
			}
		}

#if (defined(DNP_ONLY) || defined(CITIZEN_ONLY))
		{
			char buf[256];
			buf[0] = 0;
			libusb_get_string_descriptor_ascii(dev, desc->iManufacturer, (unsigned char*)buf, STR_LEN_MAX);
			sanitize_string(buf);
#ifdef DNP_ONLY  /* Only allow DNP printers to work. */
			if (strncmp(buf, "Dai", 3)) /* "Dai Nippon Printing" */
				return CUPS_BACKEND_FAILED;
#endif
#ifdef CITIZEN_ONLY   /* Only allow CITIZEN printers to work. */
			if (strncmp(buf, "CIT", 3)) /* "CITIZEN SYSTEMS" */
				return CUPS_BACKEND_FAILED;
#endif
		}
#endif
	} else {
		ctx->ver_major = 3;
		ctx->ver_minor = 0;
		ctx->version = strdup("UNKNOWN");
		switch(ctx->type) {
		case P_DNP_DS80D:
			ctx->duplex_media = 200;
			/* Intentional fallthrough */
		case P_DNP_DS80:
		case P_DNP_DS820:
			ctx->media = 510; /* 8x12 */
			break;
		case P_DNP_DSRX1:
			ctx->media = 310; /* 6x8 */
			break;
		default:
			ctx->media = 400; /* 6x9 */
			break;
		}

		if (getenv("MEDIA_CODE"))
			ctx->media = atoi(getenv("MEDIA_CODE"));
	}

	/* Per-printer options */
	switch (ctx->type) {
	case P_DNP_DS40:
		ctx->native_width = 1920;
		ctx->max_height = 5480;
		ctx->supports_6x9 = 1;
		if (FW_VER_CHECK(1,04))
			ctx->supports_counterp = 1;
		if (FW_VER_CHECK(1,30))
			ctx->supports_matte = 1;
		if (FW_VER_CHECK(1,40))
			ctx->supports_2x6 = 1;
		if (FW_VER_CHECK(1,50))
			ctx->supports_3x5x2 = 1;
		if (FW_VER_CHECK(1,60))
			ctx->supports_fullcut = ctx->supports_6x6 = 1; // No 5x5!
		break;
	case P_DNP_DS80:
	case P_DNP_DS80D:
		ctx->native_width = 2560;
		ctx->max_height = 7536;
		if (FW_VER_CHECK(1,02))
			ctx->supports_counterp = 1;
		if (FW_VER_CHECK(1,30))
			ctx->supports_matte = 1;
		break;
	case P_DNP_DSRX1:
		ctx->native_width = 1920;
		ctx->max_height = 5480;
		ctx->supports_counterp = 1;
		ctx->supports_matte = 1;
		if (FW_VER_CHECK(1,10))
			ctx->supports_2x6 = ctx->supports_mqty_default = 1;
                if (FW_VER_CHECK(1,20))
			ctx->supports_3x5x2 = 1;
		if (FW_VER_CHECK(2,00)) { /* AKA RX1HS */
			ctx->needs_mlot = 1;
			ctx->supports_mediaoffset = 1;
			ctx->supports_iserial = 1;
		}
		if (FW_VER_CHECK(2,06)) {
			ctx->supports_5x5 = ctx->supports_6x6 = 1;
		}
		break;
	case P_CITIZEN_OP900II:
		ctx->native_width = 1920;
		ctx->max_height = 5480;
		ctx->supports_counterp = 1;
		ctx->supports_matte = 1;
		ctx->supports_mqty_default = 1;
		ctx->supports_6x9 = 1;
		if (FW_VER_CHECK(1,11))
			ctx->supports_2x6 = 1;
		break;
	case P_CITIZEN_CW01:
		ctx->native_width = 2048;
		ctx->max_height = 5480;
		ctx->supports_6x9 = 1;
		break;
	case P_DNP_DS620:
		ctx->native_width = 1920;
		ctx->max_height = 5480;
		ctx->correct_count = 1;
		ctx->supports_counterp = 1;
		ctx->supports_matte = 1;
		ctx->supports_2x6 = 1;
		ctx->supports_fullcut = 1;
		ctx->supports_mqty_default = 1;
		if (strchr(ctx->version, 'A'))
			ctx->supports_rewind = 0;
		else
			ctx->supports_rewind = 1;
		ctx->supports_standby = 1;
		ctx->supports_iserial = 1;
		ctx->supports_6x6 = 1;
		ctx->supports_5x5 = 1;
		ctx->supports_lowspeed = 1;
		if (FW_VER_CHECK(0,30))
			ctx->supports_3x5x2 = 1;
		if (FW_VER_CHECK(1,10))
			ctx->supports_6x9 = ctx->supports_6x4_5 = 1;
		if (FW_VER_CHECK(1,20))
			ctx->supports_adv_fullcut = ctx->supports_advmatte = 1;
		if (FW_VER_CHECK(1,30))
			ctx->supports_luster = 1;
		if (FW_VER_CHECK(1,33))
			ctx->supports_media_ext = 1;
		if (FW_VER_CHECK(1,52))
			ctx->supports_finematte = 1;
		break;
	case P_DNP_DS820:
		ctx->native_width = 2560;
		ctx->max_height = 7536;
		ctx->correct_count = 1;
		ctx->supports_counterp = 1;
		ctx->supports_matte = 1;
		ctx->supports_fullcut = 1;
		ctx->supports_mqty_default = 1;
		if (strchr(ctx->version, 'A'))
			ctx->supports_rewind = 0;
		else
			ctx->supports_rewind = 1;
		ctx->supports_standby = 1;
		ctx->supports_iserial = 1;
		ctx->supports_adv_fullcut = 1;
		ctx->supports_advmatte = 1;
		ctx->supports_luster = 1;
		ctx->supports_finematte = 1;
		ctx->supports_printspeed = 1;
		ctx->supports_lowspeed = 1;
		ctx->supports_highdensity = 1;
		if (FW_VER_CHECK(0,50))
			ctx->supports_gamma = 1;
		break;
	default:
		ERROR("Unknown printer type %d\n", ctx->type);
		return CUPS_BACKEND_FAILED;
	}

	ctx->last_matte = -1;
#ifdef STATE_DIR
	/* Check our current job's lamination vs previous job. */
	{
		/* Load last matte status from file */
		char buf[64];
		FILE *f;
		snprintf(buf, sizeof(buf), STATE_DIR "/%s-last", ctx->serno);
		f = fopen(buf, "r");
		if (f) {
			fscanf(f, "%d", &ctx->last_matte);
			fclose(f);
		}
	}
#endif

	if (test_mode < TEST_MODE_NOATTACH && ctx->supports_mediaoffset) {
		/* Get Media Offset */
		struct dnpds40_cmd cmd;
		uint8_t *resp;
		int len = 0;

		dnpds40_build_cmd(&cmd, "INFO", "MEDIA_OFFSET", 0);
		resp = dnpds40_resp_cmd(ctx, &cmd, &len);
		if (resp) {
			ctx->mediaoffset = atoi((char*)resp+4);
			free(resp);
		} else {
			return CUPS_BACKEND_FAILED;
		}
	} else if (!ctx->correct_count) {
		ctx->mediaoffset = 50;
	}

	if (test_mode < TEST_MODE_NOATTACH && ctx->supports_mqty_default) {
		struct dnpds40_cmd cmd;
		uint8_t *resp;
		int len = 0;

		dnpds40_build_cmd(&cmd, "INFO", "MQTY_DEFAULT", 0);

		resp = dnpds40_resp_cmd(ctx, &cmd, &len);
		if (resp) {
			dnpds40_cleanup_string((char*)resp, len);
			ctx->media_count_new = atoi((char*)resp+4);
			free(resp);
			ctx->media_count_new -= ctx->mediaoffset;
		} else {
			return CUPS_BACKEND_FAILED;
		}
	} else {
		/* Look it up for legacy models & FW */
		switch (ctx->type) {
		case P_DNP_DS40:
			switch (ctx->media) {
			case 200: // L
				ctx->media_count_new = 460;
				break;
			case 210: // 2L
				ctx->media_count_new = 230;
				break;
			case 300: // PC
				ctx->media_count_new = 400;
				break;
			case 310: // A5
				ctx->media_count_new = 200;
				break;
			case 400: // A5W
				ctx->media_count_new = 180;
				break;
			default:
				ctx->media_count_new = 0;
				break;
			}
			break;
		case P_DNP_DSRX1:
			switch (ctx->media) {
			case 210: // 2L
				ctx->media_count_new = 350;
				break;
			case 300: // PC
				ctx->media_count_new = 700;
				break;
			case 310: // A5
				ctx->media_count_new = 350;
				break;
			default:
				ctx->media_count_new = 0;
				break;
			}
			break;
		case P_CITIZEN_OP900II:
			switch (ctx->media) {
			case 210: // 2L
				ctx->media_count_new = 350;
				break;
			case 300: // PC
				ctx->media_count_new = 600;
				break;
			case 310: // A5
				ctx->media_count_new = 300;
				break;
			case 400: // A5W
				ctx->media_count_new = 280;
				break;
			default:
				ctx->media_count_new = 0;
				break;
			}
			break;
		case P_CITIZEN_CW01:
			switch (ctx->media) {
			case 300: // PC
				ctx->media_count_new = 600;
				break;
			case 350: // 2L
				ctx->media_count_new = 230;
				break;
			case 400: // A5W
				ctx->media_count_new = 280;
				break;
			default:
				ctx->media_count_new = 0;
				break;
			}
			break;
		case P_DNP_DS80:
		case P_DNP_DS80D:
			switch (ctx->media) {
			case 500: // 8x10
				ctx->media_count_new = 130;
				break;
			case 510: // 8x12
				ctx->media_count_new = 110;
				break;
			default:
				ctx->media_count_new = 0;
				break;
			}
			break;
		default:
			ctx->media_count_new = 0;
			break;
		}
	}

	/* Fill out marker structure */
	ctx->marker.color = "#00FFFF#FF00FF#FFFF00";
	ctx->marker.name = dnpds40_media_types(ctx->media);
	ctx->marker.levelmax = ctx->media_count_new;
	ctx->marker.levelnow = -2;

	return CUPS_BACKEND_OK;
}

static void dnpds40_cleanup_job(const void *vjob) {
	const struct dnpds40_printjob *job = vjob;

	if (job->databuf)
		free(job->databuf);

	free((void*)job);
}

static void dnpds40_teardown(void *vctx) {
	struct dnpds40_ctx *ctx = vctx;

	if (!ctx)
		return;

	if (test_mode < TEST_MODE_NOATTACH && ctx->type == P_DNP_DS80D) {
		struct dnpds40_cmd cmd;

		/* Check to see if last print was the front side
		   of a duplex job, and if so, cancel things so we're done */
		if (ctx->last_multicut >= 200 &&
		    ctx->last_multicut < 300) {
			dnpds40_build_cmd(&cmd, "CNTRL", "DUPLEX_CANCEL", 0);
			if ((dnpds40_do_cmd(ctx, &cmd, NULL, 0)) != 0)
				return;
		}
	}

	if (ctx->serno)
		free(ctx->serno);
	if (ctx->version)
		free(ctx->version);
	free(ctx);
}

#define MAX_PRINTJOB_LEN (((ctx->native_width*ctx->max_height+1024+54+10))*3+1024) /* Worst-case, YMC */

static int dnpds40_read_parse(void *vctx, const void **vjob, int data_fd, int copies) {
	struct dnpds40_ctx *ctx = vctx;
	int run = 1;
	char buf[9] = { 0 };

	struct dnpds40_printjob *job = NULL;
	struct dyesub_joblist *list;
	int can_combine = 0;

	if (!ctx)
		return CUPS_BACKEND_FAILED;

	job = malloc(sizeof(*job));
	if (!job) {
		ERROR("Memory allocation failure!\n");
		return CUPS_BACKEND_RETRY_CURRENT;
	}
	memset(job, 0, sizeof(*job));
	job->printspeed = -1;
	job->copies = copies;

	/* There's no way to figure out the total job length in advance, we
	   have to parse the stream until we get to the image plane data,
	   and even then the stream can contain arbitrary commands later.

	   So instead, we allocate a buffer of the maximum possible length,
	   then parse the incoming stream until we hit the START command at
	   the end of the job.
	*/

	job->databuf = malloc(MAX_PRINTJOB_LEN);
	if (!job->databuf) {
		ERROR("Memory allocation failure!\n");
		return CUPS_BACKEND_RETRY_CURRENT;
	}

	while (run) {
		int remain, i, j;
		/* Read in command header */
		i = read(data_fd, job->databuf + job->datalen,
			 sizeof(struct dnpds40_cmd));
		if (i < 0) {
			dnpds40_cleanup_job(job);
			return i;
		}
		if (i == 0)
			break;
		if (i < (int) sizeof(struct dnpds40_cmd)) {
			dnpds40_cleanup_job(job);
			return CUPS_BACKEND_CANCEL;
		}

		if (job->databuf[job->datalen + 0] != 0x1b ||
		    job->databuf[job->datalen + 1] != 0x50) {
			struct cw01_spool_hdr hdr;
			/* See if it's the "classic" CW01 header */
			memcpy(&hdr, job->databuf + job->datalen, sizeof(hdr));
			hdr.plane_len = le32_to_cpu(hdr.plane_len);

			if (hdr.type > 0x06 ||
			    hdr.res > 0x01 ||
			    hdr.null1[0] || hdr.null1[1] || hdr.null1[2] || hdr.null1[3]) {
				ERROR("Unrecognized header data format @%d!\n", job->datalen);
				dnpds40_cleanup_job(job);
			} else {
				job->dpi = (hdr.res == DPI_600) ? 600 : 334;
				i = cw01_read_parse(job, data_fd, &hdr, i);
				if (i == CUPS_BACKEND_OK)
					goto parsed;
				else {
					dnpds40_cleanup_job(job);
					return i;
				}
			}
			return CUPS_BACKEND_CANCEL;
		}

		/* Parse out length of data chunk, if any */
		memcpy(buf, job->databuf + job->datalen + 24, 8);
		j = atoi(buf);

		/* Read in data chunk as quickly as possible */
		remain = j;
		while (remain > 0) {
			i = read(data_fd, job->databuf + job->datalen + sizeof(struct dnpds40_cmd),
				 remain);
			if (i < 0) {
				ERROR("Data Read Error: %d (%d/%d @%d)\n", i, remain, j, job->datalen);
				dnpds40_cleanup_job(job);
				return i;
			}
			if (i == 0) {
				dnpds40_cleanup_job(job);
				return 1;
			}
			job->datalen += i;
			remain -= i;
		}
		job->datalen -= j; /* Back it off */

		/* Check for some offsets */
		if(!memcmp("CNTRL QTY", job->databuf + job->datalen+2, 9)) {
			/* Ignore this.  We will insert our own later on */
			continue;
		}
		if(!memcmp("CNTRL CUTTER", job->databuf + job->datalen+2, 12)) {
			memcpy(buf, job->databuf + job->datalen + 32, 8);
			job->cutter = atoi(buf);
			/* We'll insert it ourselves later */
			continue;
		}
		if(!memcmp("CNTRL BUFFCNTRL", job->databuf + job->datalen+2, 15)) {
			/* Ignore this.  We will insert our own later on
			   if the printer and job support it. */
			continue;
		}
		if(!memcmp("CNTRL OVERCOAT", job->databuf + job->datalen+2, 14)) {
			if (ctx->supports_matte) {
				memcpy(buf, job->databuf + job->datalen + 32, 8);
				job->matte = atoi(buf);
			} else {
				WARNING("Printer FW does not support matte prints, using glossy mode\n");
			}
			/* We'll insert our own later, if appropriate */
			continue;
		}
		if(!memcmp("IMAGE MULTICUT", job->databuf + job->datalen+2, 14)) {
			memcpy(buf, job->databuf + job->datalen + 32, 8);
			job->multicut = atoi(buf);
			/* Backend automatically handles rewind support, so
			   ignore application requests to use it. */
			if (job->multicut > 400)
				job->multicut -= 400;

			/* We'll insert this ourselves later. */
			continue;
		}
		if(!memcmp("CNTRL FULL_CUTTER_SET", job->databuf + job->datalen+2, 21)) {
			if (!ctx->supports_fullcut) {
				WARNING("Printer FW does not support full cutter control!\n");
				continue;
			}

			if (ctx->type == P_DNP_DS820) {
				if (j != 24) {
					WARNING("Full cutter argument length incorrect, ignoring!\n");
					continue;
				}
			} else if (j != 16) {
				WARNING("Full cutter argument length incorrect, ignoring!\n");
				continue;
			} else if (!ctx->supports_adv_fullcut) {
				if (job->databuf[job->datalen + 32 + 12] != '0' ||
				    job->databuf[job->datalen + 32 + 13] != '0' ||
				    job->databuf[job->datalen + 32 + 14] != '0') {
					WARNING("Full cutter scrap setting not supported on this firmware, ignoring!\n");
					continue;
				}
			}
			// XXX enforce cut counts/sizes?

			job->fullcut = 1;
		}
		if(!memcmp("IMAGE YPLANE", job->databuf + job->datalen + 2, 12)) {
			uint32_t y_ppm; /* Pixels Per Meter */

			/* Validate vertical resolution */
			memcpy(&y_ppm, job->databuf + job->datalen + 32 + 42, sizeof(y_ppm));
			y_ppm = le32_to_cpu(y_ppm);

			switch (y_ppm) {
			case 11808:
				job->dpi = 300;
				break;
			case 23615:
				job->dpi = 600;
				break;
			default:
				ERROR("Unrecognized printjob resolution (%u ppm)\n", y_ppm);
				dnpds40_cleanup_job(job);
				return CUPS_BACKEND_CANCEL;
			}

			/* Validate horizontal size */
			memcpy(&y_ppm, job->databuf + job->datalen + 32 + 18, sizeof(y_ppm));
			y_ppm = le32_to_cpu(y_ppm);
			if (y_ppm != ctx->native_width) {
				ERROR("Incorrect horizontal resolution (%u), aborting!\n", y_ppm);
				dnpds40_cleanup_job(job);
				return CUPS_BACKEND_CANCEL;
			}
		}
		if(!memcmp("CNTRL PRINTSPEED", job->databuf + job->datalen + 2, 16)) {
			if (!ctx->supports_printspeed) {
				WARNING("Printer does not support PRINTSPEED\n");
				continue;
			}
			memcpy(buf, job->databuf + job->datalen + 32, 8);
			job->printspeed = atoi(buf) / 10;

			/* We'll insert this ourselves later. */
			continue;
		}

		/* This is the last block.. */
	        if(!memcmp("CNTRL START", job->databuf + job->datalen + 2, 11))
			run = 0;

		/* Add in the size of this chunk */
		job->datalen += sizeof(struct dnpds40_cmd) + j;
	}
parsed:
	/* If we have no data.. don't bother */
	if (!job->datalen) {
		dnpds40_cleanup_job(job);
		return CUPS_BACKEND_CANCEL;
	}

	/* Sanity check matte mode */
	if (job->matte == 21 && !ctx->supports_finematte) {
		WARNING("Printer FW does not support Fine Matte mode, downgrading to normal matte\n");
		job->matte = 1;
	} else if (job->matte == 22 && !ctx->supports_luster) {
		WARNING("Printer FW does not support Luster mode, downgrading to normal matte\n");
		job->matte = 1;
	} else if (job->matte > 1 && !ctx->supports_advmatte) {
		WARNING("Printer FW does not support advanced matte modes, downgrading to normal matte\n");
		job->matte = 1;
	}

	/* Pick a sane default value for printspeed if not specified */
	if (job->printspeed == -1 || job->printspeed > 3)
	{
		if (job->dpi == 600)
			job->printspeed = 1;
		else
			job->printspeed = 0;
	}
	/* And sanity-check whatever value is there */
	if (job->printspeed == 0 && job->dpi == 600) {
		job->printspeed = 1;
	} else if (job->printspeed == 1 && job->dpi == 300) {
		job->printspeed = 0;
	}

	/* Make sure MULTICUT is sane, most validation needs this */
	if (!job->multicut && ctx->type != P_CITIZEN_CW01) {
		WARNING("Missing or illegal MULTICUT command!\n");
		if (job->dpi == 300)
			job->buf_needed = 1;
		else
			job->buf_needed = 2;

		goto skip_checks;
	}

	/* Only DS80D supports Cut Paper types */
	if (job->multicut > 100 &&
	    ctx->type != P_DNP_DS80D) {
		ERROR("Only DS80D supports cut-paper sizes!\n");
		dnpds40_cleanup_job(job);
		return CUPS_BACKEND_CANCEL;
	}

	/* Figure out the number of buffers we need. */
	job->buf_needed = 1;

	if (job->dpi == 600) {
		switch(ctx->type) {
		case P_DNP_DS620:
			if (job->multicut == MULTICUT_6x9 ||
			    job->multicut == MULTICUT_6x4_5X2)
				job->buf_needed = 2;
			break;
		case P_DNP_DS80:  /* DS80/CX-W */
			if (job->matte && (job->multicut == MULTICUT_8xA4LEN ||
					   job->multicut == MULTICUT_8x4X3 ||
					   job->multicut == MULTICUT_8x8_8x4 ||
					   job->multicut == MULTICUT_8x6X2 ||
					   job->multicut == MULTICUT_8x12))
				job->buf_needed = 2;
			break;
		case P_DNP_DS80D:
			if (job->matte) {
				int mcut = job->multicut;

				if (mcut > MULTICUT_S_BACK)
					mcut -= MULTICUT_S_BACK;
				else if (mcut > MULTICUT_S_FRONT)
					mcut -= MULTICUT_S_FRONT;

				if (mcut == MULTICUT_8xA4LEN ||
				    mcut == MULTICUT_8x4X3 ||
				    mcut == MULTICUT_8x8_8x4 ||
				    mcut == MULTICUT_8x6X2 ||
				    mcut == MULTICUT_8x12)
					job->buf_needed = 2;

				if (mcut == MULTICUT_S_8x12 ||
				    mcut == MULTICUT_S_8x6X2 ||
				    mcut == MULTICUT_S_8x4X3)
					job->buf_needed = 2;
			}
			break;
		case P_DNP_DS820:
			// Nothing; all sizes only need 1 buffer
			break;
		case P_CITIZEN_CW01:
			job->buf_needed = 2;
			break;
		default: /* DS40/CX/RX1/CY/everything else */
			if (job->matte) {
				if (job->multicut == MULTICUT_6x8 ||
				    job->multicut == MULTICUT_6x9 ||
				    job->multicut == MULTICUT_6x4X2 ||
				    job->multicut == MULTICUT_5x7 ||
				    job->multicut == MULTICUT_5x3_5X2)
					job->buf_needed = 2;

			} else {
				if (job->multicut == MULTICUT_6x8 ||
				    job->multicut == MULTICUT_6x9 ||
				    job->multicut == MULTICUT_6x4X2)
					job->buf_needed = 1;
			}
			break;
		}
	}
	if (job->dpi == 334 && ctx->type != P_CITIZEN_CW01)
	{
		ERROR("Illegal resolution (%u) for printer!\n", job->dpi);
		dnpds40_cleanup_job(job);
		return CUPS_BACKEND_CANCEL;
	}

	/* Sanity-check type vs loaded media */
	if (job->multicut == 0)
		goto skip_multicut;

	if (job->multicut < 100) {
		switch(ctx->media) {
		case 200: //"5x3.5 (L)"
			if (job->multicut != MULTICUT_5x3_5) {
				ERROR("Incorrect media for job loaded (%u vs %u)\n", ctx->media, job->multicut);
				dnpds40_cleanup_job(job);
				return CUPS_BACKEND_CANCEL;
			}
			break;
		case 210: //"5x7 (2L)"
			if (job->multicut != MULTICUT_5x3_5 && job->multicut != MULTICUT_5x7 &&
			    job->multicut != MULTICUT_5x3_5X2 && job->multicut != MULTICUT_5x5) {
				ERROR("Incorrect media for job loaded (%u vs %u)\n", ctx->media, job->multicut);
				dnpds40_cleanup_job(job);
				return CUPS_BACKEND_CANCEL;
			}
			/* Only 3.5x5 on 7x5 media can be rewound */
			if (job->multicut == MULTICUT_5x3_5)
				job->can_rewind = 1;
			break;
		case 300: //"6x4 (PC)"
			if (job->multicut != MULTICUT_6x4) {
				ERROR("Incorrect media for job loaded (%u vs %u)\n", ctx->media, job->multicut);
				dnpds40_cleanup_job(job);
				return CUPS_BACKEND_CANCEL;
			}
			break;
		case 310: //"6x8 (A5)"
			if (job->multicut != MULTICUT_6x4 && job->multicut != MULTICUT_6x8 &&
			    job->multicut != MULTICUT_6x4X2 &&
			    job->multicut != MULTICUT_6x6 && job->multicut != 30) {
				ERROR("Incorrect media for job loaded (%u vs %u)\n", ctx->media, job->multicut);
				dnpds40_cleanup_job(job);
				return CUPS_BACKEND_CANCEL;
			}
			/* Only 6x4 on 6x8 media can be rewound */
			if (job->multicut == MULTICUT_6x4)
				job->can_rewind = 1;
			break;
		case 400: //"6x9 (A5W)"
			if (job->multicut != MULTICUT_6x4 && job->multicut != MULTICUT_6x8 &&
			    job->multicut != MULTICUT_6x9 && job->multicut != MULTICUT_6x4X2 &&
			    job->multicut != MULTICUT_6x6 &&
			    job->multicut != MULTICUT_6x4_5 && job->multicut != MULTICUT_6x4_5X2) {
				ERROR("Incorrect media for job loaded (%u vs %u)\n", ctx->media, job->multicut);
				dnpds40_cleanup_job(job);
				return CUPS_BACKEND_CANCEL;
			}
			/* Only 6x4 or 6x4.5 on 6x9 media can be rewound */
			if (job->multicut == MULTICUT_6x4 || job->multicut == MULTICUT_6x4_5)
				job->can_rewind = 1;
			break;
		case 500: //"8x10"
			if (ctx->type == P_DNP_DS820 &&
			    (job->multicut == MULTICUT_8x7 || job->multicut == MULTICUT_8x9)) {
				/* These are okay */
			} else if (job->multicut < MULTICUT_8x10 || job->multicut == MULTICUT_8x12 ||
			    job->multicut == MULTICUT_8x6X2 || job->multicut >= MULTICUT_8x6_8x5 ) {
				ERROR("Incorrect media for job loaded (%u vs %u)\n", ctx->media, job->multicut);
				dnpds40_cleanup_job(job);
				return CUPS_BACKEND_CANCEL;
			}

			/* 8x4, 8x5 can be rewound */
			if (job->multicut == MULTICUT_8x4 ||
			    job->multicut == MULTICUT_8x5)
				job->can_rewind = 1;
			break;
		case 510: //"8x12"
			if (job->multicut < MULTICUT_8x10 || (job->multicut > MULTICUT_8xA4LEN && !(job->multicut == MULTICUT_8x7 || job->multicut == MULTICUT_8x9))) {
				ERROR("Incorrect media for job loaded (%u vs %u)\n", ctx->media, job->multicut);
				dnpds40_cleanup_job(job);
				return CUPS_BACKEND_CANCEL;
			}

			/* 8x4, 8x5, 8x6 can be rewound */
			if (job->multicut == MULTICUT_8x4 ||
			    job->multicut == MULTICUT_8x5 ||
			    job->multicut == MULTICUT_8x6)
				job->can_rewind = 1;
			break;
		case 600: //"A4"
			if (job->multicut < MULTICUT_A5 || job->multicut > MULTICUT_A4x5X2) {
				ERROR("Incorrect media for job loaded (%u vs %u)\n", ctx->media, job->multicut);
				dnpds40_cleanup_job(job);
				return CUPS_BACKEND_CANCEL;
			}
			/* A4xn and A5 can be rewound */
			if (job->multicut == MULTICUT_A4x4 ||
			    job->multicut == MULTICUT_A4x5 ||
			    job->multicut == MULTICUT_A4x6 ||
			    job->multicut == MULTICUT_A5)
				job->can_rewind = 1;
			break;
		default:
			ERROR("Unknown media (%u vs %u)!\n", ctx->media, job->multicut);
			dnpds40_cleanup_job(job);
			return CUPS_BACKEND_CANCEL;
		}
	} else if (job->multicut < 400) {
		int mcut = job->multicut;

		switch(ctx->duplex_media) {
		case 100: //"8x10.75"
			if (mcut > MULTICUT_S_BACK)
				mcut -= MULTICUT_S_BACK;
			else if (mcut > MULTICUT_S_FRONT)
				mcut -= MULTICUT_S_FRONT;

			if (mcut == MULTICUT_S_8x12 ||
			    mcut == MULTICUT_S_8x6X2 ||
			    mcut == MULTICUT_S_8x4X3) {
				ERROR("Incorrect media for job loaded (%u vs %u)\n", ctx->duplex_media, job->multicut);
				dnpds40_cleanup_job(job);
				return CUPS_BACKEND_CANCEL;
			}
			break;
		case 200: //"8x12"
			/* Everything is legal */
			break;
		default:
			ERROR("Unknown duplexer media (%u vs %u)!\n", ctx->duplex_media, job->multicut);
			dnpds40_cleanup_job(job);
			return CUPS_BACKEND_CANCEL;
		}
	} else {
		ERROR("Multicut value out of range! (%u)\n", job->multicut);
		dnpds40_cleanup_job(job);
		return CUPS_BACKEND_CANCEL;
	}

	/* Additional santity checks, make sure printer support exists */
	if (!ctx->supports_6x6 && job->multicut == MULTICUT_6x6) {
		ERROR("Printer does not support 6x6 prints, aborting!\n");
		dnpds40_cleanup_job(job);
		return CUPS_BACKEND_CANCEL;
	}

	if (!ctx->supports_5x5 && job->multicut == MULTICUT_5x5) {
		ERROR("Printer does not support 5x5 prints, aborting!\n");
		dnpds40_cleanup_job(job);
		return CUPS_BACKEND_CANCEL;
	}

	if ((job->multicut == MULTICUT_6x4_5 || job->multicut == MULTICUT_6x4_5X2) &&
	    !ctx->supports_6x4_5) {
		ERROR("Printer does not support 6x4.5 prints, aborting!\n");
		dnpds40_cleanup_job(job);
		return CUPS_BACKEND_CANCEL;
	}

	if (job->multicut == MULTICUT_6x9 && !ctx->supports_6x9) {
		ERROR("Printer does not support 6x9 prints, aborting!\n");
		dnpds40_cleanup_job(job);
		return CUPS_BACKEND_CANCEL;
	}

	if (job->multicut == MULTICUT_5x3_5X2 && !ctx->supports_3x5x2) {
		ERROR("Printer does not support 3.5x5*2 prints, aborting!\n");
		dnpds40_cleanup_job(job);
		return CUPS_BACKEND_CANCEL;
	}

skip_multicut:

	if (job->fullcut && !ctx->supports_adv_fullcut &&
	    job->multicut != MULTICUT_6x8) {
		ERROR("Printer does not support full control on sizes other than 6x8, aborting!\n");
		dnpds40_cleanup_job(job);
		return CUPS_BACKEND_CANCEL;
	}

	if (job->fullcut && job->cutter) {
		WARNING("Cannot simultaneously use FULL_CUTTER and CUTTER, using the former\n");
		job->cutter = 0;
	}

	if (job->cutter == 120) {
		if (job->multicut == MULTICUT_6x4 || job->multicut == MULTICUT_6x8) {
			if (!ctx->supports_2x6) {
				ERROR("Printer does not support 2x6 prints, aborting!\n");
				dnpds40_cleanup_job(job);
				return CUPS_BACKEND_CANCEL;
			}
		} else {
			ERROR("Printer only supports legacy 2-inch cuts on 4x6 or 8x6 jobs!");
			dnpds40_cleanup_job(job);
			return CUPS_BACKEND_CANCEL;
		}
	}

skip_checks:
	DEBUG("job->dpi %u matte %d mcut %u cutter %d/%d, bufs %d spd %d\n",
	      job->dpi, job->matte, job->multicut, job->cutter, job->fullcut, job->buf_needed, job->printspeed);

	list = dyesub_joblist_create(&dnpds40_backend, ctx);

	can_combine = job->can_rewind; /* Any rewindable size can be stacked */

	/* Try to combine prints */
	if (copies > 1 && can_combine) {
		struct dnpds40_printjob *combined;
		combined = combine_jobs(job, job);
		if (combined) {
			combined->copies = job->copies / 2;
			combined->can_rewind = 0;
			dyesub_joblist_addjob(list, combined);

			if (job->copies & 1) {
				job->copies = 1;
			} else {
				dnpds40_cleanup_job(job);
				job = NULL;
			}
		}
	}
	if (job) {
		dyesub_joblist_addjob(list, job);
	}

	*vjob = list;

	return CUPS_BACKEND_OK;
}

static int dnpds40_main_loop(void *vctx, const void *vjob) {
	struct dnpds40_ctx *ctx = vctx;
	int ret;
	struct dnpds40_cmd cmd;
	uint8_t *resp;
	int len = 0;
	uint8_t *ptr;
	char buf[9];
	int status;
	int buf_needed;
	int multicut;
	int count = 0;
	int manual_copies = 0;
	int copies;

	const struct dnpds40_printjob *job = vjob;

	if (!ctx)
		return CUPS_BACKEND_FAILED;
	if (!job)
		return CUPS_BACKEND_FAILED;

	buf_needed = job->buf_needed;
	multicut = job->multicut;
	copies = job->copies;

	/* If we switch major overcoat modes, we need both buffers */
	if (!!job->matte != ctx->last_matte)
		buf_needed = 2;

	if (job->cutter == 120) {
		/* Work around firmware bug on DS40 where if we run out
		   of media, we can't resume the job without losing the
		   cutter setting. */
		// XXX add version test? what about other printers?
		manual_copies = 1;
	}

	/* RX1HS requires HS media, but the only way to tell is that the
	   HS media reports a lot code, while the non-HS media does not. */
	if (ctx->needs_mlot) {
		/* Get Media Lot */
		dnpds40_build_cmd(&cmd, "INFO", "MLOT", 0);

		resp = dnpds40_resp_cmd(ctx, &cmd, &len);
		if (!resp)
			return CUPS_BACKEND_FAILED;

		dnpds40_cleanup_string((char*)resp, len);

		len = strlen((char*)resp);
		free(resp);
		if (!len) {
			ERROR("Media does not report a valid lot number (non-HS media in RX1HS?)\n");
			return CUPS_BACKEND_STOP;
		}
	}

top:

	/* Query status */
	dnpds40_build_cmd(&cmd, "STATUS", "", 0);
	resp = dnpds40_resp_cmd(ctx, &cmd, &len);
	if (!resp)
		return CUPS_BACKEND_FAILED;
	dnpds40_cleanup_string((char*)resp, len);
	status = atoi((char*)resp);
	free(resp);

	/* Figure out what's going on */
	switch(status) {
	case 0:	/* Idle; we can continue! */
	case 1: /* Printing */
	{
		int bufs;

		/* Query buffer state */
		dnpds40_build_cmd(&cmd, "INFO", "FREE_PBUFFER", 0);
		resp = dnpds40_resp_cmd(ctx, &cmd, &len);

		if (!resp)
			return CUPS_BACKEND_FAILED;

		dnpds40_cleanup_string((char*)resp, len);
		/* Check to see if we have sufficient buffers */
		bufs = atoi(((char*)resp)+3);
		free(resp);
		if (bufs < buf_needed) {
			INFO("Insufficient printer buffers (%d vs %d), retrying...\n", bufs, buf_needed);
			sleep(1);
			goto top;
		}
		break;
	}
	case 500: /* Cooling print head */
	case 510: /* Cooling paper motor */
		INFO("Printer cooling down...\n");
		sleep(1);
		goto top;
	case 900:
		INFO("Waking printer up from standby...\n");
		// XXX do someting here?
		break;
	case 1000: /* Cover open */
	case 1010: /* No Scrap Box */
	case 1100: /* Paper End */
	case 1200: /* Ribbon End */
	case 1300: /* Paper Jam */
	case 1400: /* Ribbon Error */
		WARNING("Printer not ready: %s, please correct...\n", dnpds40_statuses(status));
		sleep(1);
		goto top;
	case 1500: /* Paper definition error */
		ERROR("Paper definition error, aborting job\n");
		return CUPS_BACKEND_CANCEL;
	case 1600: /* Data error */
		ERROR("Data error, aborting job\n");
		return CUPS_BACKEND_CANCEL;
	default:
		ERROR("Fatal Printer Error: %d => %s, halting queue!\n", status, dnpds40_statuses(status));
		return CUPS_BACKEND_HOLD;
	}

	{
		/* Figure out remaining native prints */
		ctx->marker.levelnow = dnpds40_query_mqty(ctx);
		if (ctx->marker.levelnow < 0)
			return CUPS_BACKEND_FAILED;
		dump_markers(&ctx->marker, 1, 0);

		count = ctx->marker.levelnow; // For logic below.

		/* See if we can rewind to save media */
		if (job->can_rewind && ctx->supports_rewind) {
			/* Tell printer to use rewind */
			multicut += 400;

			/* Get Media remaining */
			dnpds40_build_cmd(&cmd, "INFO", "RQTY", 0);

			resp = dnpds40_resp_cmd(ctx, &cmd, &len);
			if (!resp)
				return CUPS_BACKEND_FAILED;

			dnpds40_cleanup_string((char*)resp, len);
			count = atoi((char*)resp+4);
			free(resp);
		}

		if (ctx->type == P_CITIZEN_CW01) {
			/* Get Vertical resolution */
			dnpds40_build_cmd(&cmd, "INFO", "RESOLUTION_V", 0);

			resp = dnpds40_resp_cmd(ctx, &cmd, &len);
			if (!resp)
				return CUPS_BACKEND_FAILED;

			dnpds40_cleanup_string((char*)resp, len);

#if 0  // XXX Fix 600dpi support on CW01
			// have to read the last DPI, and send the correct CWD over?
			if (ctx->dpi == 600 && strcmp("RV0334", *char*)resp) {
				ERROR("600DPI prints not yet supported, need 600DPI CWD load");
				return CUPS_BACKEND_CANCEL;
			}
#endif
			free(resp);
		}

		/* Verify we have sufficient media for prints */

#if 0 // disabled this to allow error to be reported on the printer panel
		if (count < 1) {
			ERROR("Printer out of media, please correct!\n");
			return CUPS_BACKEND_STOP;
		}
#endif
		if (count < copies) {
			WARNING("Printer does not have sufficient remaining media (%d) to complete job (%d)\n", copies, count);
		}
	}

	/* Store our last multicut state */
	ctx->last_multicut = multicut;

	/* Tell printer how many copies to make */
	snprintf(buf, sizeof(buf), "%07d\r", manual_copies ? 1 : copies);
	dnpds40_build_cmd(&cmd, "CNTRL", "QTY", 8);
	if ((ret = dnpds40_do_cmd(ctx, &cmd, (uint8_t*)buf, 8)))
		return CUPS_BACKEND_FAILED;

	if (!manual_copies)
		copies = 1;

	/* Enable job resumption on correctable errors */
	if (ctx->supports_matte) {
		snprintf(buf, sizeof(buf), "%08d", 1);
		/* DS80D does not support BUFFCNTRL when using
		   cut media; all others support this */
		if (ctx->type != P_DNP_DS80D ||
		    multicut < 100) {
			dnpds40_build_cmd(&cmd, "CNTRL", "BUFFCNTRL", 8);
			if ((ret = dnpds40_do_cmd(ctx, &cmd, (uint8_t*)buf, 8)))
				return CUPS_BACKEND_FAILED;
		}
	}

	/* Set overcoat parameters if appropriate */
	if (ctx->supports_matte) {
		snprintf(buf, sizeof(buf), "%08d", job->matte);
		dnpds40_build_cmd(&cmd, "CNTRL", "OVERCOAT", 8);
		if ((ret = dnpds40_do_cmd(ctx, &cmd, (uint8_t*)buf, 8)))
			return CUPS_BACKEND_FAILED;
	}

	/* Program in the cutter setting */
	if (job->cutter) {
		snprintf(buf, sizeof(buf), "%08d", job->cutter);
		dnpds40_build_cmd(&cmd, "CNTRL", "CUTTER", 8);
		if ((ret = dnpds40_do_cmd(ctx, &cmd, (uint8_t*)buf, 8)))
			return CUPS_BACKEND_FAILED;
	}

	/* Send over the printspeed if appropriate */
	if (ctx->supports_printspeed) {
		snprintf(buf, sizeof(buf), "%08d", job->printspeed * 10);
		dnpds40_build_cmd(&cmd, "CNTRL", "PRINTSPEED", 8);
		if ((ret = dnpds40_do_cmd(ctx, &cmd, (uint8_t*)buf, 8)))
			return CUPS_BACKEND_FAILED;
	}

	/* Program in the multicut setting, if one exists */
	if (multicut) {
		snprintf(buf, sizeof(buf), "%08u", multicut);
		dnpds40_build_cmd(&cmd, "IMAGE", "MULTICUT", 8);
		if ((ret = dnpds40_do_cmd(ctx, &cmd, (uint8_t*)buf, 8)))
			return CUPS_BACKEND_FAILED;
	}

	/* Finally, send the stream over as individual data chunks */
	ptr = job->databuf;
	while(ptr && ptr < (job->databuf + job->datalen)) {
		int i;
		buf[8] = 0;
		memcpy(buf, ptr + 24, 8);
		i = atoi(buf) + 32;

		if ((ret = send_data(ctx->dev, ctx->endp_down,
				     ptr, i)))
			return CUPS_BACKEND_FAILED;

		ptr += i;
	}
	sleep(1);  /* Give things a moment */

	if (fast_return && !manual_copies) {
		INFO("Fast return mode enabled.\n");
	} else {
		INFO("Waiting for job to complete...\n");
		int started = 0;

		while (1) {
			/* Query status */
			dnpds40_build_cmd(&cmd, "STATUS", "", 0);
			resp = dnpds40_resp_cmd(ctx, &cmd, &len);
			if (!resp)
				return CUPS_BACKEND_FAILED;
			dnpds40_cleanup_string((char*)resp, len);
			status = atoi((char*)resp);
			free(resp);

			/* If we're idle or there's an error..*/
			if (status == 0 && started)
				break;
			if (status)
				started = 1;
			if (status >= 1000) {
				ERROR("Printer encountered error: %s\n", dnpds40_statuses(status));
				break;
			}
			sleep(1);
		}

		/* Figure out remaining native prints */
		dnpds40_build_cmd(&cmd, "INFO", "MQTY", 0);

		resp = dnpds40_resp_cmd(ctx, &cmd, &len);
		if (!resp)
			return CUPS_BACKEND_FAILED;

		dnpds40_cleanup_string((char*)resp, len);

		count = atoi((char*)resp+4);
		free(resp);

		if (count) {
			/* Old-sk00l models report one less than they should */
			if (!ctx->correct_count)
				count++;

			count -= ctx->mediaoffset;
		}
		ctx->marker.levelnow = count;
		dump_markers(&ctx->marker, 1, 0);
	}

	/* Clean up */
	if (terminate)
		copies = 1;

	INFO("Print complete (%d copies remaining)\n", copies - 1);

	if (copies && --copies) {
		/* No need to wait on buffers due to matte switching */
		buf_needed = job->buf_needed;
		goto top;
	}

	/* Finally, account for overcoat mode of last print */
	ctx->last_matte = !!job->matte;
#ifdef STATE_DIR
	{
		/* Store last matte status into file */
		char buf[64];
		FILE *f;
		snprintf(buf, sizeof(buf), STATE_DIR "/%s-last", ctx->serno);
		f = fopen(buf, "w");
		if (f) {
			fprintf(f, "%08d", ctx->last_matte);
			fclose(f);
		}
	}
#endif

	return CUPS_BACKEND_OK;
}

static int dnpds40_get_sensors(struct dnpds40_ctx *ctx)
{
	struct dnpds40_cmd cmd;
	uint8_t *resp;
	int len = 0;
	char *tok;

	/* Get Sensor Info */
	dnpds40_build_cmd(&cmd, "INFO", "SENSOR", 0);

	resp = dnpds40_resp_cmd(ctx, &cmd, &len);
	if (!resp)
		return CUPS_BACKEND_FAILED;

	dnpds40_cleanup_string((char*)resp, len);

	tok = strtok((char*)resp, "; -");
	do {
		char *val = strtok(NULL, "; -");

		if (!strcmp("HDT", tok)) {
			INFO("Head Temperature   : %s\n", val);
		} else if (!strcmp("MDT", tok)) {
			INFO("Media Temperature  : %s\n", val);
		} else if (!strcmp("PMK", tok)) {
			INFO("Paper Mark         : %s\n", val);
		} else if (!strcmp("RML", tok)) {
			INFO("Ribbon Mark Left   : %s\n", val);
		} else if (!strcmp("RMC", tok)) {
			INFO("Ribbon Mark Right  : %s\n", val);
		} else if (!strcmp("RMR", tok)) {
			INFO("Ribbon Mark Center : %s\n", val);
		} else if (!strcmp("PSZ", tok)) {
			INFO("Paper Size         : %s\n", val);
		} else if (!strcmp("PNT", tok)) {
			INFO("Paper Notch        : %s\n", val);
		} else if (!strcmp("PJM", tok)) {
			INFO("Paper Jam          : %s\n", val);
		} else if (!strcmp("PED", tok)) {
			INFO("Paper End          : %s\n", val);
		} else if (!strcmp("PET", tok)) {
			INFO("Paper Empty        : %s\n", val);
		} else if (!strcmp("HDV", tok)) {
			INFO("Head Voltage       : %s\n", val);
		} else if (!strcmp("HMD", tok)) {
			INFO("Humidity           : %s\n", val);
		} else if (!strcmp("RP1", tok)) {
			INFO("Roll Paper End 1   : %s\n", val);
		} else if (!strcmp("RP2", tok)) {
			INFO("Roll Paper End 2   : %s\n", val);
		} else if (!strcmp("CSR", tok)) {
			INFO("Color Sensor Red   : %s\n", val);
		} else if (!strcmp("CSG", tok)) {
			INFO("Color Sensor Green : %s\n", val);
		} else if (!strcmp("CSB", tok)) {
			INFO("Color Sensor Blue  : %s\n", val);
		} else {
			INFO("Unknown Sensor: '%s' '%s'\n",
			     tok, val);
		}
	} while ((tok = strtok(NULL, "; -")) != NULL);

	free(resp);

	return CUPS_BACKEND_OK;
}

static int dnpds40_get_info(struct dnpds40_ctx *ctx)
{
	struct dnpds40_cmd cmd;
	uint8_t *resp;
	int len = 0;

	INFO("Model: %s\n", dnpds40_printer_type(ctx->type));

	/* Serial number already queried */
	INFO("Serial Number: %s\n", ctx->serno);

	/* Firmware version already queried */
	INFO("Firmware Version: %s\n", ctx->version);

	/* Figure out Duplexer */
	if (ctx->type == P_DNP_DS80D) {
		dnpds40_build_cmd(&cmd, "INFO", "UNIT_FVER", 0);

		resp = dnpds40_resp_cmd(ctx, &cmd, &len);
		if (!resp)
			return CUPS_BACKEND_FAILED;

		dnpds40_cleanup_string((char*)resp, len);

		INFO("Duplexer Version: %s\n", resp);

		free(resp);
	}

	if (ctx->type == P_CITIZEN_CW01) {
		/* Get Horizonal resolution */
		dnpds40_build_cmd(&cmd, "INFO", "RESOLUTION_H", 0);

		resp = dnpds40_resp_cmd(ctx, &cmd, &len);
		if (!resp)
			return CUPS_BACKEND_FAILED;

		dnpds40_cleanup_string((char*)resp, len);

		INFO("Horizontal Resolution: %s dpi\n", (char*)resp + 3);

		free(resp);

		/* Get Vertical resolution */
		dnpds40_build_cmd(&cmd, "INFO", "RESOLUTION_V", 0);

		resp = dnpds40_resp_cmd(ctx, &cmd, &len);
		if (!resp)
			return CUPS_BACKEND_FAILED;

		dnpds40_cleanup_string((char*)resp, len);

		INFO("Vertical Resolution: %s dpi\n", (char*)resp + 3);

		free(resp);

		/* Get Color Control Data Version */
		dnpds40_build_cmd(&cmd, "TBL_RD", "Version", 0);

		resp = dnpds40_resp_cmd(ctx, &cmd, &len);
		if (!resp)
			return CUPS_BACKEND_FAILED;

		dnpds40_cleanup_string((char*)resp, len);

		INFO("Color Data Version: %s ", (char*)resp);

		free(resp);

		/* Get Color Control Data Checksum */
		dnpds40_build_cmd(&cmd, "MNT_RD", "CTRLD_CHKSUM", 0);

		resp = dnpds40_resp_cmd(ctx, &cmd, &len);
		if (!resp)
			return CUPS_BACKEND_FAILED;

		dnpds40_cleanup_string((char*)resp, len);

		DEBUG2("(%s)\n", (char*)resp);

		free(resp);
	}

	/* Get Media Color offset */
	dnpds40_build_cmd(&cmd, "INFO", "MCOLOR", 0);

	resp = dnpds40_resp_cmd(ctx, &cmd, &len);
	if (!resp)
		return CUPS_BACKEND_FAILED;

	dnpds40_cleanup_string((char*)resp, len);

	INFO("Media Color Offset: Y %u M %u C %u L %u\n", *(resp+2), *(resp+3),
	     *(resp+4), *(resp+5));

	free(resp);

	/* Get Media Class */
	dnpds40_build_cmd(&cmd, "INFO", "MEDIA_CLASS", 0);

	resp = dnpds40_resp_cmd(ctx, &cmd, &len);
	if (!resp)
		return CUPS_BACKEND_FAILED;

	dnpds40_cleanup_string((char*)resp, len);

	INFO("Media Class: %d\n", atoi((char*)resp + 4));

	free(resp);

	/* Get Media Lot */
	dnpds40_build_cmd(&cmd, "INFO", "MLOT", 0);

	resp = dnpds40_resp_cmd(ctx, &cmd, &len);
	if (!resp)
		return CUPS_BACKEND_FAILED;

	dnpds40_cleanup_string((char*)resp, len);

	INFO("Media Lot Code: %s\n", (char*)resp+2);
	free(resp);

	/* Get Media ID Set (?) */
	dnpds40_build_cmd(&cmd, "MNT_RD", "MEDIA_ID_SET", 0);

	resp = dnpds40_resp_cmd(ctx, &cmd, &len);
	if (!resp)
		return CUPS_BACKEND_FAILED;

	dnpds40_cleanup_string((char*)resp, len);

	INFO("Media ID: %d\n", atoi((char*)resp+4));

	free(resp);

	if (ctx->type == P_CITIZEN_CW01)
		goto skip;

	/* Get Ribbon ID code (?) */
	dnpds40_build_cmd(&cmd, "MNT_RD", "RIBBON_ID_CODE", 0);

	resp = dnpds40_resp_cmd(ctx, &cmd, &len);
	if (!resp)
		return CUPS_BACKEND_FAILED;

	dnpds40_cleanup_string((char*)resp, len);

	INFO("Ribbon ID: %s\n", (char*)resp);

	free(resp);

	/* Figure out control data and checksums */

	/* 300 DPI */
	dnpds40_build_cmd(&cmd, "TBL_RD", "CWD300_Version", 0);

	resp = dnpds40_resp_cmd(ctx, &cmd, &len);
	if (!resp)
		return CUPS_BACKEND_FAILED;

	dnpds40_cleanup_string((char*)resp, len);

	INFO("300 DPI Color Data: %s ", (char*)resp);

	free(resp);

	dnpds40_build_cmd(&cmd, "TBL_RD", "CWD300_Checksum", 0);

	resp = dnpds40_resp_cmd(ctx, &cmd, &len);
	if (!resp)
		return CUPS_BACKEND_FAILED;

	dnpds40_cleanup_string((char*)resp, len);

	DEBUG2("(%s)\n", (char*)resp);

	free(resp);

	/* 600 DPI */
	dnpds40_build_cmd(&cmd, "TBL_RD", "CWD600_Version", 0);

	resp = dnpds40_resp_cmd(ctx, &cmd, &len);
	if (!resp)
		return CUPS_BACKEND_FAILED;

	dnpds40_cleanup_string((char*)resp, len);

	INFO("600 DPI Color Data: %s ", (char*)resp);

	free(resp);

	dnpds40_build_cmd(&cmd, "TBL_RD", "CWD600_Checksum", 0);

	resp = dnpds40_resp_cmd(ctx, &cmd, &len);
	if (!resp)
		return CUPS_BACKEND_FAILED;

	dnpds40_cleanup_string((char*)resp, len);

	DEBUG2("(%s)\n", (char*)resp);

	free(resp);

	if (ctx->supports_lowspeed) {
		/* "Low Speed" */
		dnpds40_build_cmd(&cmd, "TBL_RD", "CWD610_Version", 0);

		resp = dnpds40_resp_cmd(ctx, &cmd, &len);
		if (!resp)
			return CUPS_BACKEND_FAILED;

		dnpds40_cleanup_string((char*)resp, len);

		INFO("Low Speed Color Data: %s ", (char*)resp);

		free(resp);

		dnpds40_build_cmd(&cmd, "TBL_RD", "CWD610_Checksum", 0);

		resp = dnpds40_resp_cmd(ctx, &cmd, &len);
		if (!resp)
			return CUPS_BACKEND_FAILED;

		dnpds40_cleanup_string((char*)resp, len);

		DEBUG2("(%s)\n", (char*)resp);

		free(resp);
	}
	if (ctx->supports_highdensity) {
		uint8_t buf[5];
		int i = 0;

		snprintf((char*)buf, sizeof(buf), "%04d", i);

		/* "High Density" */
		dnpds40_build_cmd(&cmd, "TBL_RD", "CWD620_Version", 4);

		resp = dnpds40_resp_cmd2(ctx, &cmd, &len, buf, 4);
		if (!resp)
			return CUPS_BACKEND_FAILED;

		dnpds40_cleanup_string((char*)resp, len);

		INFO("High Density Color Data: %s ", (char*)resp);

		free(resp);

		dnpds40_build_cmd(&cmd, "TBL_RD", "CWD620_Checksum", 4);

		resp = dnpds40_resp_cmd2(ctx, &cmd, &len, buf, 4);
		if (!resp)
			return CUPS_BACKEND_FAILED;

		dnpds40_cleanup_string((char*)resp, len);

		DEBUG2("(%s)\n", (char*)resp);

		free(resp);
	}
	if (ctx->supports_gamma) {
		/* "Low Speed" */
		dnpds40_build_cmd(&cmd, "TBL_RD", "CTRLD_GAMMA16", 0);

		resp = dnpds40_resp_cmd(ctx, &cmd, &len);
		if (!resp)
			return CUPS_BACKEND_FAILED;

		dnpds40_cleanup_string((char*)resp, len);

		INFO("Gamma Correction Data Checksum: %s\n", (char*)resp);

		free(resp);
	}

	if (ctx->supports_standby) {
		/* Get Standby stuff */
		int i;

		dnpds40_build_cmd(&cmd, "MNT_RD", "STANDBY_TIME", 0);

		resp = dnpds40_resp_cmd(ctx, &cmd, &len);
		if (!resp)
			return CUPS_BACKEND_FAILED;

		dnpds40_cleanup_string((char*)resp, len);
		i = atoi((char*)resp);

		INFO("Standby Transition time: %d minutes\n", i);

		free(resp);

		/* Get Media End Keep */
		dnpds40_build_cmd(&cmd, "MNT_RD", "END_KEEP_MODE", 0);

		resp = dnpds40_resp_cmd(ctx, &cmd, &len);
		if (!resp)
			return CUPS_BACKEND_FAILED;

		dnpds40_cleanup_string((char*)resp, len);
		i = atoi((char*)resp);
		INFO("Media End kept across power cycles: %s\n",
		     i ? "Yes" : "No");

		free(resp);
	}

	if (ctx->supports_iserial) {
		int i;
		/* Get USB serial descriptor status */
		dnpds40_build_cmd(&cmd, "MNT_RD", "USB_ISERI_SET", 0);

		resp = dnpds40_resp_cmd(ctx, &cmd, &len);
		if (!resp)
			return CUPS_BACKEND_FAILED;

		dnpds40_cleanup_string((char*)resp, len);
		i = atoi((char*)resp);

		INFO("Report Serial Number in USB descriptor: %s\n",
		     i ? "Yes" : "No");

		free(resp);
	}

skip:
	return CUPS_BACKEND_OK;
}

static int dnpds40_get_status(struct dnpds40_ctx *ctx)
{
	struct dnpds40_cmd cmd;
	uint8_t *resp;
	int len = 0;
	int count;

	/* Generate command */
	dnpds40_build_cmd(&cmd, "STATUS", "", 0);

	resp = dnpds40_resp_cmd(ctx, &cmd, &len);
	if (!resp)
		return CUPS_BACKEND_FAILED;

	dnpds40_cleanup_string((char*)resp, len);
	count = atoi((char*)resp);

	INFO("Printer Status: %s (%d)\n", dnpds40_statuses(count), count);

	free(resp);

	/* Figure out Duplexer */
	if (ctx->type == P_DNP_DS80D) {
		dnpds40_build_cmd(&cmd, "INFO", "UNIT_STATUS", 0);

		resp = dnpds40_resp_cmd(ctx, &cmd, &len);
		if (!resp)
			return CUPS_BACKEND_FAILED;

		dnpds40_cleanup_string((char*)resp, len);
		count = atoi((char*)resp);

		INFO("Duplexer Status: %s\n", dnpds80_duplex_statuses(count));

		free(resp);
	}

	/* Get remaining print quantity */
	dnpds40_build_cmd(&cmd, "INFO", "PQTY", 0);

	resp = dnpds40_resp_cmd(ctx, &cmd, &len);
	if (!resp)
		return CUPS_BACKEND_FAILED;

	dnpds40_cleanup_string((char*)resp, len);

	INFO("Prints remaining in job: %d\n", atoi((char*)resp + 4));

	free(resp);

	/* Generate command */
	dnpds40_build_cmd(&cmd, "INFO", "FREE_PBUFFER", 0);

	resp = dnpds40_resp_cmd(ctx, &cmd, &len);
	if (!resp)
		return CUPS_BACKEND_FAILED;

	dnpds40_cleanup_string((char*)resp, len);

	INFO("Free Buffers: %d\n", atoi((char*)resp + 3));
	free(resp);

	/* Report media */
	INFO("Media Type: %s\n", dnpds40_media_types(ctx->media));

	if (ctx->supports_media_ext) {
		int type;
		dnpds40_build_cmd(&cmd, "INFO", "MEDIA_EXT_CODE", 0);
		resp = dnpds40_resp_cmd(ctx, &cmd, &len);
		if (!resp)
			return CUPS_BACKEND_FAILED;

		dnpds40_cleanup_string((char*)resp, len);
		*(resp+2) = 0;  // Only the first two chars are used.
		type = atoi((char*)resp);
		INFO("Media Code: %s\n", dnpds620_media_extension_code(type));
		free(resp);
	}

	/* Try to figure out media subtype */
	if (ctx->type == P_DNP_DS820) {
		int type;
		dnpds40_build_cmd(&cmd, "INFO", "MEDIA_CLASS_RFID", 0);
		resp = dnpds40_resp_cmd(ctx, &cmd, &len);
		if (!resp)
			return CUPS_BACKEND_FAILED;

		dnpds40_cleanup_string((char*)resp, len);
		type = atoi((char*)resp);
		INFO("Media Subtype: %s\n", dnpds820_media_subtypes(type));
		free(resp);
	}

	/* Report Cut Media */
	if (ctx->type == P_DNP_DS80D)
		INFO("Duplex Media Type: %s\n", dnpds80_duplex_media_types(ctx->media));

	if (ctx->media_count_new)
		INFO("Native Prints Available on New Media: %u\n", ctx->media_count_new);

	/* Get Media remaining */
	count = dnpds40_query_mqty(ctx);
	if (count < 0)
		return CUPS_BACKEND_FAILED;

	INFO("Native Prints Remaining on Media: %d\n", count);

	if (ctx->supports_rewind) {
		/* Get Media remaining */
		dnpds40_build_cmd(&cmd, "INFO", "RQTY", 0);

		resp = dnpds40_resp_cmd(ctx, &cmd, &len);
		if (!resp)
			return CUPS_BACKEND_FAILED;

		dnpds40_cleanup_string((char*)resp, len);

		count = atoi((char*)resp+4);
		free(resp);
	} else {
		// Do nothing, re-use native print count.
	}
	INFO("Half-Size Prints Remaining on Media: %d\n", count);

	return 0;
}

static int dnpds40_get_counters(struct dnpds40_ctx *ctx)
{
	struct dnpds40_cmd cmd;
	uint8_t *resp;
	int len = 0;

	/* Generate command */
	dnpds40_build_cmd(&cmd, "MNT_RD", "COUNTER_LIFE", 0);

	resp = dnpds40_resp_cmd(ctx, &cmd, &len);
	if (!resp)
		return CUPS_BACKEND_FAILED;

	dnpds40_cleanup_string((char*)resp, len);

	INFO("Lifetime Counter: %d\n", atoi((char*)resp+2));

	free(resp);

	if (ctx->type == P_DNP_DS620 ||
	    ctx->type == P_DNP_DS820) {
		/* Generate command */
		dnpds40_build_cmd(&cmd, "MNT_RD", "COUNTER_HEAD", 0);

		resp = dnpds40_resp_cmd(ctx, &cmd, &len);
		if (!resp)
			return CUPS_BACKEND_FAILED;

		dnpds40_cleanup_string((char*)resp, len);

		INFO("Head Counter: %d\n", atoi((char*)resp+2));

		free(resp);
	}

	/* Generate command */
	dnpds40_build_cmd(&cmd, "MNT_RD", "COUNTER_A", 0);

	resp = dnpds40_resp_cmd(ctx, &cmd, &len);
	if (!resp)
		return CUPS_BACKEND_FAILED;

	dnpds40_cleanup_string((char*)resp, len);

	INFO("A Counter: %d\n", atoi((char*)resp+2));

	free(resp);

	/* Generate command */
	dnpds40_build_cmd(&cmd, "MNT_RD", "COUNTER_B", 0);

	resp = dnpds40_resp_cmd(ctx, &cmd, &len);
	if (!resp)
		return CUPS_BACKEND_FAILED;

	dnpds40_cleanup_string((char*)resp, len);

	INFO("B Counter: %d\n", atoi((char*)resp+2));

	free(resp);

	if (ctx->supports_counterp) {
		/* Generate command */
		dnpds40_build_cmd(&cmd, "MNT_RD", "COUNTER_P", 0);

		resp = dnpds40_resp_cmd(ctx, &cmd, &len);
		if (!resp)
			return CUPS_BACKEND_FAILED;

		dnpds40_cleanup_string((char*)resp, len);

		INFO("P Counter: %d\n", atoi((char*)resp+2));

		free(resp);
	}

	if (ctx->supports_matte) {
		/* Generate command */
		dnpds40_build_cmd(&cmd, "MNT_RD", "COUNTER_M", 0);

		resp = dnpds40_resp_cmd(ctx, &cmd, &len);
		if (!resp)
			return CUPS_BACKEND_FAILED;

		dnpds40_cleanup_string((char*)resp, len);

		INFO("M Counter: %d\n", atoi((char*)resp+2));

		free(resp);

		/* Generate command */
		dnpds40_build_cmd(&cmd, "MNT_RD", "COUNTER_MATTE", 0);

		resp = dnpds40_resp_cmd(ctx, &cmd, &len);
		if (!resp)
			return CUPS_BACKEND_FAILED;

		dnpds40_cleanup_string((char*)resp, len);

		INFO("Matte Counter: %d\n", atoi((char*)resp+4));

		free(resp);
	}

	if (ctx->type == P_DNP_DS80D) {
		dnpds40_build_cmd(&cmd, "MNT_RD", "COUNTER_DUPLEX", 0);

		resp = dnpds40_resp_cmd(ctx, &cmd, &len);
		if (!resp)
			return CUPS_BACKEND_FAILED;

		dnpds40_cleanup_string((char*)resp, len);

		INFO("Duplexer Counter: %d\n", atoi((char*)resp));

		free(resp);
	}

	return CUPS_BACKEND_OK;
}

static int dnpds40_clear_counter(struct dnpds40_ctx *ctx, char counter)
{
	struct dnpds40_cmd cmd;
	char msg[4];
	int ret;

	/* Generate command */
	dnpds40_build_cmd(&cmd, "MNT_WT", "COUNTER_CLEAR", 4);
	msg[0] = 'C';
	msg[1] = counter;
	msg[2] = 0x0d; /* ie carriage return, ASCII '\r' */
	msg[3] = 0x00;

	if ((ret = dnpds40_do_cmd(ctx, &cmd, (uint8_t*)msg, 4)))
		return ret;

	return 0;
}

static int dnpds40_cancel_job(struct dnpds40_ctx *ctx)
{
	struct dnpds40_cmd cmd;
	int ret;

	/* Generate command */
	dnpds40_build_cmd(&cmd, "CNTRL", "CANCEL", 0);

	if ((ret = dnpds40_do_cmd(ctx, &cmd, NULL, 0)))
		return ret;

	return 0;
}

static int dnpds40_reset_printer(struct dnpds40_ctx *ctx)
{
	struct dnpds40_cmd cmd;
	int ret;

	/* Generate command */
	dnpds40_build_cmd(&cmd, "CNTRL", "PRINTER_RESET", 0);

	if ((ret = dnpds40_do_cmd(ctx, &cmd, NULL, 0)))
		return ret;

	return 0;
}

static int dnpds620_standby_mode(struct dnpds40_ctx *ctx, int delay)
{
	struct dnpds40_cmd cmd;
	char msg[9];
	int ret;

	/* Generate command */
	dnpds40_build_cmd(&cmd, "MNT_WT", "STANDBY_TIME", 8);
	snprintf(msg, sizeof(msg), "%08d", delay);

	if ((ret = dnpds40_do_cmd(ctx, &cmd, (uint8_t*)msg, 8)))
		return ret;

	return 0;
}

static int dnpds620_media_keep_mode(struct dnpds40_ctx *ctx, int delay)
{
	struct dnpds40_cmd cmd;
	char msg[9];
	int ret;

	/* Generate command */
	dnpds40_build_cmd(&cmd, "MNT_WT", "END_KEEP_MODE", 4);
	snprintf(msg, sizeof(msg), "%02d\r", delay);

	if ((ret = dnpds40_do_cmd(ctx, &cmd, (uint8_t*)msg, 4)))
		return ret;

	return 0;
}

static int dnpds620_iserial_mode(struct dnpds40_ctx *ctx, int enable)
{
	struct dnpds40_cmd cmd;
	char msg[9];
	int ret;

	/* Generate command */
	dnpds40_build_cmd(&cmd, "MNT_WT", "USB_ISERI_SET", 4);
	snprintf(msg, sizeof(msg), "%02d\r", enable);

	if ((ret = dnpds40_do_cmd(ctx, &cmd, (uint8_t*)msg, 8)))
		return ret;

	return 0;
}

static int dnpds40_set_counter_p(struct dnpds40_ctx *ctx, char *arg)
{
	struct dnpds40_cmd cmd;
	char msg[9];
	int i = atoi(arg);
	int ret;

	/* Generate command */
	dnpds40_build_cmd(&cmd, "MNT_WT", "COUNTERP_SET", 8);
	snprintf(msg, sizeof(msg), "%08d", i);

	if ((ret = dnpds40_do_cmd(ctx, &cmd, (uint8_t*)msg, 8)))
		return ret;

	return 0;
}

static void dnpds40_cmdline(void)
{
	DEBUG("\t\t[ -i ]           # Query printer info\n");
	DEBUG("\t\t[ -I ]           # Query sensor  info\n");
	DEBUG("\t\t[ -k num ]       # Set standby time (1-99 minutes, 0 disables)\n");
	DEBUG("\t\t[ -K num ]       # Keep Media Status Across Power Cycles (1 on, 0 off)\n");
	DEBUG("\t\t[ -n ]           # Query counters\n");
	DEBUG("\t\t[ -N A|B|M ]     # Clear counter A/B/M\n");
	DEBUG("\t\t[ -p num ]       # Set counter P\n");
	DEBUG("\t\t[ -R ]           # Reset printer\n");
	DEBUG("\t\t[ -s ]           # Query status\n");
	DEBUG("\t\t[ -x num ]       # Set USB iSerialNumber Reporting (1 on, 0 off)\n");
	DEBUG("\t\t[ -X ]           # Cancel current print job\n");
}

static int dnpds40_cmdline_arg(void *vctx, int argc, char **argv)
{
	struct dnpds40_ctx *ctx = vctx;
	int i, j = 0;

	if (!ctx)
		return -1;

	while ((i = getopt(argc, argv, GETOPT_LIST_GLOBAL "iIk:K:nN:p:Rsx:X")) >= 0) {
		switch(i) {
		GETOPT_PROCESS_GLOBAL
		case 'i':
			j = dnpds40_get_info(ctx);
			break;
		case 'I':
			j = dnpds40_get_sensors(ctx);
			break;
		case 'k': {
			int time = atoi(optarg);
			if (!ctx->supports_standby) {
				ERROR("Printer does not support standby\n");
				j = -1;
				break;
			}
			if (time < 0 || time > 99) {
				ERROR("Value out of range (0-99)");
				j = -1;
				break;
			}
			j = dnpds620_standby_mode(ctx, time);
			break;
		}
		case 'K': {
			int keep = atoi(optarg);
			if (!ctx->supports_standby) {
				ERROR("Printer does not support media keep mode\n");
				j = -1;
				break;
			}
			if (keep < 0 || keep > 1) {
				ERROR("Value out of range (0-1)");
				j = -1;
				break;
			}
			j = dnpds620_media_keep_mode(ctx, keep);
			break;
		}
		case 'n':
			j = dnpds40_get_counters(ctx);
			break;
		case 'N':
			if (optarg[0] != 'A' &&
			    optarg[0] != 'B' &&
			    optarg[0] != 'M')
				return CUPS_BACKEND_FAILED;
			if (optarg[0] == 'M' && !ctx->supports_matte) {
				ERROR("Printer FW does not support matte functions, please update!\n");
				return CUPS_BACKEND_FAILED;
			}
			j = dnpds40_clear_counter(ctx, optarg[0]);
			break;
		case 'p':
			if (!ctx->supports_counterp) {
				ERROR("Printer FW dows not support P counter!\n");
				return CUPS_BACKEND_FAILED;
			}
			j = dnpds40_set_counter_p(ctx, optarg);
			break;
		case 'R': {
			j = dnpds40_reset_printer(ctx);
			break;
		}
		case 's': {
			j = dnpds40_get_status(ctx);
			break;
		}
		case 'x': {
			int enable = atoi(optarg);
			if (!ctx->supports_iserial) {
				ERROR("Printer does not support USB iSerialNumber reporting\n");
				j = -1;
				break;
			}
			if (enable < 0 || enable > 1) {
				ERROR("Value out of range (0-1)");
				j = -1;
				break;
			}
			j = dnpds620_iserial_mode(ctx, enable);
			break;
		}
		case 'X': {
			j = dnpds40_cancel_job(ctx);
			break;
		}
		default:
			break;  /* Ignore completely */
		}

		if (j) return j;
	}

	return 0;
}

static int dnpds40_query_markers(void *vctx, struct marker **markers, int *count)
{
	struct dnpds40_ctx *ctx = vctx;

	*markers = &ctx->marker;
	*count = 1;

	ctx->marker.levelnow = dnpds40_query_mqty(ctx);
	if (ctx->marker.levelnow < 0)
		return CUPS_BACKEND_FAILED;

	return CUPS_BACKEND_OK;
}

static const char *dnpds40_prefixes[] = {
	"dnp_citizen", "dnpds40",  // Family names, do *not* nuke.
	"dnp-ds40", "dnp-ds80", "dnp-ds80dx", "dnp-ds620", "dnp-ds820", "dnp-dsrx1",
	"citizen-cw-01", "citizen-cw-02", "citizen-cx-02",
	// backwards compatibility
	"dnpds80", "dnpds80dx", "dnpds620", "dnpds820", "dnprx1",
	"citizencw01", "citizencw02", "citizencx02",
	// These are all extras.
	"citizen-cx", "citizen-cx-w", "citizen-cy", "citizen-cy-02",
	"citizen-op900", "citizen-op900ii",
	NULL
};

#define USB_VID_CITIZEN   0x1343
#define USB_PID_DNP_DS40  0x0003 // Also Citizen CX
#define USB_PID_DNP_DS80  0x0004 // Also Citizen CX-W and Mitsubishi CP-3800DW
#define USB_PID_DNP_DSRX1 0x0005 // Also Citizen CY
#define USB_PID_DNP_DS80D 0x0008

#define USB_PID_CITIZEN_CW01 0x0002 // Maybe others?
#define USB_PID_CITIZEN_CW02 0x0006 // Also OP900II
#define USB_PID_CITIZEN_CX02 0x000A

#define USB_VID_DNP       0x1452
#define USB_PID_DNP_DS620 0x8b01
#define USB_PID_DNP_DS820 0x9001

/* Exported */
struct dyesub_backend dnpds40_backend = {
	.name = "DNP DS-series / Citizen C-series",
	.version = "0.109",
	.uri_prefixes = dnpds40_prefixes,
	.flags = BACKEND_FLAG_JOBLIST,
	.cmdline_usage = dnpds40_cmdline,
	.cmdline_arg = dnpds40_cmdline_arg,
	.init = dnpds40_init,
	.attach = dnpds40_attach,
	.teardown = dnpds40_teardown,
	.read_parse = dnpds40_read_parse,
	.cleanup_job = dnpds40_cleanup_job,
	.main_loop = dnpds40_main_loop,
	.query_serno = dnpds40_query_serno,
	.query_markers = dnpds40_query_markers,
	.devices = {
		{ USB_VID_CITIZEN, USB_PID_DNP_DS40, P_DNP_DS40, NULL, "dnp-ds40"},  // Also Citizen CX
		{ USB_VID_CITIZEN, USB_PID_DNP_DS80, P_DNP_DS80, NULL, "dnp-ds80"},  // Also Citizen CX-W and Mitsubishi CP-3800DW
		{ USB_VID_CITIZEN, USB_PID_DNP_DS80D, P_DNP_DS80D, NULL, "dnp-ds80dx"},
		{ USB_VID_CITIZEN, USB_PID_DNP_DSRX1, P_DNP_DSRX1, NULL, "dnp-dsrx1"}, // Also Citizen CY
		{ USB_VID_DNP, USB_PID_DNP_DS620, P_DNP_DS620, NULL, "dnp-ds620"},
		{ USB_VID_DNP, USB_PID_DNP_DS820, P_DNP_DS820, NULL, "dnp-ds820"},
		{ USB_VID_CITIZEN, USB_PID_CITIZEN_CW01, P_CITIZEN_CW01, NULL, "citizen-cw-01"}, // Also OP900 ?
		{ USB_VID_CITIZEN, USB_PID_CITIZEN_CW02, P_CITIZEN_OP900II, NULL, "citizen-cw-02"}, // Also OP900II
		{ USB_VID_CITIZEN, USB_PID_CITIZEN_CX02, P_DNP_DS620, NULL, "citizen-cx-02"},
		{ 0, 0, 0, NULL, NULL}
	}
};

/* Legacy CW-01 spool file support */

static int cw01_read_parse(struct dnpds40_printjob *job, int data_fd,
			   struct cw01_spool_hdr *hdr, int read_data)
{
	int i, remain;
	uint32_t j;
	uint8_t *buf;
	uint8_t plane_hdr[14];

	remain = hdr->plane_len * 3;
	buf = malloc(remain);
	if (!buf) {
		ERROR("Memory allocation failure!\n");
		return CUPS_BACKEND_RETRY_CURRENT;
	}
	j = read_data - sizeof(*hdr);
	memcpy(buf, job->databuf, j);
	remain -= j;
	/* Read in the remaining spool data */
	while (remain) {
		i = read(data_fd, buf + j, remain);

		if (i < 0) {
			free(buf);
			return i;
		}

		remain -= i;
		j += i;
	}

	/* Generate plane header (same for all planes) */
	j = cpu_to_le32(hdr->plane_len) + 24;
	memset(plane_hdr, 0, sizeof(plane_hdr));
	plane_hdr[0] = 0x42;
	plane_hdr[1] = 0x4d;
	memcpy(plane_hdr + 2, &j, sizeof(j));
	plane_hdr[10] = 0x40;
	plane_hdr[11] = 0x04;

	/* Okay, generate a new stream into job->databuf! */
#if 0
	job->datalen += sprintf((char*)job->databuf + job->datalen,
				"\033PCNTRL QTY             00000008%07d\r", hdr->copies);
	job->datalen += sprintf((char*)job->databuf + job->datalen,
				"\033PCNTRL CUTTER          0000000800000000");
#else
	/* QTY is stripped from the stream, and CUTTER is stashed away */
	job->cutter = 0;
#endif

	j = 0;

	/* Y plane */
	job->datalen += sprintf((char*)job->databuf + job->datalen,
				"\033PIMAGE YPLANE          %08u", hdr->plane_len + 24);
	memcpy(job->databuf + job->datalen, plane_hdr, sizeof(plane_hdr));
	job->datalen += sizeof(plane_hdr);
	memcpy(job->databuf + job->datalen, buf + j, hdr->plane_len);
	job->datalen += hdr->plane_len;
	j += hdr->plane_len;
	memset(job->databuf + job->datalen, 0, 10);
	job->datalen += 10;

	/* M plane */
	job->datalen += sprintf((char*)job->databuf + job->datalen,
				"\033PIMAGE MPLANE          %08u", hdr->plane_len + 24);
	memcpy(job->databuf + job->datalen, plane_hdr, sizeof(plane_hdr));
	job->datalen += sizeof(plane_hdr);
	memcpy(job->databuf + job->datalen, buf + j, hdr->plane_len);
	job->datalen += hdr->plane_len;
	j += hdr->plane_len;
	memset(job->databuf + job->datalen, 0, 10);
	job->datalen += 10;

	/* C plane */
	job->datalen += sprintf((char*)job->databuf + job->datalen,
				"\033PIMAGE CPLANE          %08u", hdr->plane_len + 24);
	memcpy(job->databuf + job->datalen, plane_hdr, sizeof(plane_hdr));
	job->datalen += sizeof(plane_hdr);
	memcpy(job->databuf + job->datalen, buf + j, hdr->plane_len);
	job->datalen += hdr->plane_len;
	j += hdr->plane_len;
	memset(job->databuf + job->datalen, 0, 10);
	job->datalen += 10;

	/* Start */
	job->datalen += sprintf((char*)job->databuf + job->datalen,
				"\033PCNTRL START                   ");

	/* We're done */
	free(buf);

	return CUPS_BACKEND_OK;
}

/*

Basic spool file format for CW01

TT RR NN 00 XX XX XX XX  00 00 00 00              <- FILE header.

  NN          : copies (0x01 or more)
  RR          : resolution; 0 == 334 dpi, 1 == 600dpi
  TT          : type 0x02 == 4x6, 0x01 == 5x3.5
  XX XX XX XX : plane length (LE)
                plane length * 3 + 12 == file length.

Followed by three planes, each with this header:

28 00 00 00 00 08 00 00  RR RR 00 00 01 00 08 00
00 00 00 00 00 00 00 00  5a 33 00 00 YY YY 00 00
00 01 00 00 00 00 00 00

  RR RR       : rows in LE format
  YY YY       : 0x335a (334dpi) or 0x5c40 (600dpi)

Followed by 1024 bytes of color tables:

 ff ff ff 00 ... 00 00 00 00

1024+40 = 1064 bytes of header per plane.

Always have 2048 columns of data.

followed by (2048 * rows) bytes of data.

*/