summaryrefslogtreecommitdiff
path: root/src/main/print-canon.c
blob: 6968ff07ac96744865d974e8f2947731ea732ef5 (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
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
/*
 * "$Id: print-canon.c,v 1.523 2012/05/25 17:52:30 gernot2270 Exp $"
 *
 *   Print plug-in CANON BJL driver for the GIMP.
 *
 *   Copyright 1997-2000 Michael Sweet (mike@easysw.com),
 *	Robert Krawitz (rlk@alum.mit.edu) and
 *      Andy Thaller (thaller@ph.tum.de)
 *
 *   Copyright (c) 2006 - 2007 Sascha Sommer (saschasommer@freenet.de)
 *
 *   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, write to the Free Software
 *   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

/*
 * This file must include only standard C header files.  The core code must
 * compile on generic platforms that don't support glib, gimp, gtk, etc.
 */

/*
 * Large parts of this file (mainly the ink handling) is based on
 * print-escp2.c -- refer to README.new-printer on how to adjust the colors
 * for a certain model.
 */

/* TODO-LIST
 *
 *   * adjust the colors of all supported models
 *
 */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <gutenprint/gutenprint.h>
#include "gutenprint-internal.h"
#include <gutenprint/gutenprint-intl-internal.h>
#include <string.h>
#include <stdio.h>
#if defined(HAVE_VARARGS_H) && !defined(HAVE_STDARG_H)
#include <varargs.h>
#else
#include <stdarg.h>
#endif
#ifdef HAVE_LIMITS_H
#include <limits.h>
#endif
#include <math.h>

#include "print-canon.h"

#ifndef MIN
#  define MIN(a,b) (((a)<(b)) ? (a) : (b))
#endif /* !MIN */
#ifndef MAX
#  define MAX(a, b) ((a) > (b) ? (a) : (b))
#endif /* !MAX */

/* set this to 1 to see errors in make, set to 0 (normal) to avoid noise */
#define ERRPRINT 0

static int
pack_pixels(unsigned char* buf,int len)
{
  int read_pos = 0;
  int write_pos = 0;
  int shift = 6;
  while(read_pos < len)
  {
    /* read 5pixels a 2 bit */
    unsigned short value = buf[read_pos] << 8;
    if(read_pos+1 < len)
      value += buf[read_pos + 1];
    if(shift)       /*6,4,2,0*/
      value >>= shift;
    /* write 8bit value representing the 10 bit pixel combination */
    buf[write_pos] = tentoeight[value & 1023];
    ++write_pos;
    if(shift == 0)
    {
      shift = 6;
      read_pos += 2;
    }
    else
    {
      shift -= 2;
      ++read_pos;
    }
  }
  return write_pos;
}

/* model peculiarities */
#define CANON_CAP_MSB_FIRST  0x02ul    /* how to send data           */
#define CANON_CAP_a          0x04ul
#define CANON_CAP_b          0x08ul
#define CANON_CAP_q          0x10ul
#define CANON_CAP_m          0x20ul
#define CANON_CAP_d          0x40ul
#define CANON_CAP_t          0x80ul
#define CANON_CAP_c          0x100ul
#define CANON_CAP_p          0x200ul
#define CANON_CAP_l          0x400ul
#define CANON_CAP_r          0x800ul
#define CANON_CAP_g          0x1000ul
#define CANON_CAP_px         0x2000ul
#define CANON_CAP_rr         0x4000ul
#define CANON_CAP_I          0x8000ul
#define CANON_CAP_T          0x10000ul /* not sure of this yet! */
#define CANON_CAP_P          0x20000ul
#define CANON_CAP_DUPLEX     0x40000ul
#define CANON_CAP_XML        0x80000ul /* not sure of this yet */
#define CANON_CAP_CARTRIDGE  0x100000ul /* not sure of this yet */
#define CANON_CAP_M          0x200000ul /* not sure of this yet */
#define CANON_CAP_S          0x400000ul /* not sure of this yet */
#define CANON_CAP_cart       0x800000ul /* BJC printers with Color, Black, Photo options */
#define CANON_CAP_BORDERLESS 0x1000000ul /* borderless printing */
#define CANON_CAP_NOBLACK    0x2000000ul /* no Black cartridge selection */

#define CANON_CAP_STD0 (CANON_CAP_b|CANON_CAP_c|CANON_CAP_d|\
                        CANON_CAP_l|CANON_CAP_q|CANON_CAP_t)

#define CANON_CAP_STD1 (CANON_CAP_b|CANON_CAP_c|CANON_CAP_d|CANON_CAP_l|\
                        CANON_CAP_m|CANON_CAP_p|CANON_CAP_q|CANON_CAP_t)

#include "canon-inks.h"
#include "canon-modes.h"
#include "canon-media.h"
#include "canon-media-mode.h"
#include "canon-printers.h"

typedef struct {
    char name;
    const canon_ink_t* props;
    unsigned char* buf;
    unsigned char* comp_buf_offset;
    unsigned int buf_length;
    unsigned int delay;
} canon_channel_t;

typedef struct
{
  const canon_mode_t* mode; 
  const canon_slot_t* slot;
  const canon_paper_t *pt;
  /* cartridge selection for CANON_CAP_T and CANON_CAP_cart */
  const char *ink_set;
  const canon_modeuse_t* modeuse;
  /* final inks used for output, after selection process completed */
  unsigned int used_inks;
  int num_channels;
  int quality;
  canon_channel_t* channels;
  char* channel_order;
  const canon_cap_t *caps;
  unsigned char *comp_buf;
  unsigned char *fold_buf;
  int delay_max;
  int buf_length_max;
  int length;
  int out_width;
  int out_height;
  int page_width;
  int page_height;
  int top;
  int left;
  int emptylines;
  int ncolors; /* number of colors to print with */
  int physical_xdpi, nozzle_ydpi, stepper_ydpi;
  int nozzles;   /* count of inkjets for one pass */
  int nozzle_separation;
  int horizontal_passes;
  int vertical_passes;
  int vertical_oversample;
  int *head_offset;
  int last_pass_offset;
  int bidirectional; /* tells us if we are allowed to print bidirectional */
  int direction;     /* stores the last direction of the print head */
  int weave_bits[4];
  const char *duplex_str;
  int is_first_page;
  double cd_inner_radius;
  double cd_outer_radius;
} canon_privdata_t;

const canon_modeuse_t* select_media_modes(stp_vars_t *v, const canon_paper_t* media_type,const canon_modeuselist_t* mlist);
int compare_mode_valid(stp_vars_t *v,const canon_mode_t* mode,const canon_modeuse_t* muse, const canon_modeuselist_t* mlist);
const canon_mode_t* suitable_mode_monochrome(stp_vars_t *v,const canon_modeuse_t* muse,const canon_cap_t *caps,int quality,const char *duplex_mode);
const canon_mode_t* find_first_matching_mode_monochrome(stp_vars_t *v,const canon_modeuse_t* muse,const canon_cap_t *caps,const char *duplex_mode);
const canon_mode_t* find_first_matching_mode(stp_vars_t *v,const canon_modeuse_t* muse,const canon_cap_t *caps,const char *duplex_mode);
const canon_mode_t* suitable_mode_color(stp_vars_t *v,const canon_modeuse_t* muse,const canon_cap_t *caps,int quality,const char *duplex_mode);
const canon_mode_t* find_first_matching_mode_color(stp_vars_t *v,const canon_modeuse_t* muse,const canon_cap_t *caps,const char *duplex_mode);
const canon_mode_t* suitable_mode_photo(stp_vars_t *v,const canon_modeuse_t* muse,const canon_cap_t *caps,int quality,const char *duplex_mode);
const canon_mode_t* find_first_matching_mode_photo(stp_vars_t *v,const canon_modeuse_t* muse,const canon_cap_t *caps,const char *duplex_mode);
const canon_mode_t* suitable_mode_general(stp_vars_t *v,const canon_modeuse_t* muse,const canon_cap_t *caps,int quality,const char *duplex_mode);
const char* find_ink_type(stp_vars_t *v,const canon_mode_t* mode,const char *printing_mode);
const canon_mode_t* canon_check_current_mode(stp_vars_t *v);

static void canon_write_line(stp_vars_t *v);

static void canon_advance_paper(stp_vars_t *, int);
static void canon_flush_pass(stp_vars_t *, int, int);
static void canon_write_multiraster(stp_vars_t *v,canon_privdata_t* pd,int y);

static const stp_parameter_t the_parameters[] =
{
  {
    "PageSize", N_("Page Size"), "Color=No,Category=Basic Printer Setup",
    N_("Size of the paper being printed to"),
    STP_PARAMETER_TYPE_STRING_LIST, STP_PARAMETER_CLASS_CORE,
    STP_PARAMETER_LEVEL_BASIC, 1, 1, STP_CHANNEL_NONE, 1, 0
  },
  {
    "MediaType", N_("Media Type"), "Color=Yes,Category=Basic Printer Setup",
    N_("Type of media (plain paper, photo paper, etc.)"),
    STP_PARAMETER_TYPE_STRING_LIST, STP_PARAMETER_CLASS_FEATURE,
    STP_PARAMETER_LEVEL_BASIC, 1, 1, STP_CHANNEL_NONE, 1, 0
  },
  {
    "InputSlot", N_("Media Source"), "Color=No,Category=Basic Printer Setup",
    N_("Source (input slot) of the media"),
    STP_PARAMETER_TYPE_STRING_LIST, STP_PARAMETER_CLASS_FEATURE,
    STP_PARAMETER_LEVEL_BASIC, 1, 1, STP_CHANNEL_NONE, 1, 0
  },
  {
    "CDInnerRadius", N_("CD Hub Size"), "Color=No,Category=Basic Printer Setup",
    N_("Print only outside of the hub of the CD, or all the way to the hole"),
    STP_PARAMETER_TYPE_STRING_LIST, STP_PARAMETER_CLASS_FEATURE,
    STP_PARAMETER_LEVEL_BASIC, 1, 1, STP_CHANNEL_NONE, 1, 0
  },
  {
    "CDOuterDiameter", N_("CD Size (Custom)"), "Color=No,Category=Basic Printer Setup",
    N_("Variable adjustment for the outer diameter of CD"),
    STP_PARAMETER_TYPE_DIMENSION, STP_PARAMETER_CLASS_FEATURE,
    STP_PARAMETER_LEVEL_ADVANCED, 1, 1, STP_CHANNEL_NONE, 1, 0
  },
  {
    "CDInnerDiameter", N_("CD Hub Size (Custom)"), "Color=No,Category=Basic Printer Setup",
    N_("Variable adjustment to the inner hub of the CD"),
    STP_PARAMETER_TYPE_DIMENSION, STP_PARAMETER_CLASS_FEATURE,
    STP_PARAMETER_LEVEL_ADVANCED, 1, 1, STP_CHANNEL_NONE, 1, 0
  },
  {
    "CDXAdjustment", N_("CD Horizontal Fine Adjustment"), "Color=No,Category=Advanced Printer Setup",
    N_("Fine adjustment to horizontal position for CD printing"),
    STP_PARAMETER_TYPE_DIMENSION, STP_PARAMETER_CLASS_FEATURE,
    STP_PARAMETER_LEVEL_ADVANCED, 1, 1, STP_CHANNEL_NONE, 1, 0
  },
  {
    "CDYAdjustment", N_("CD Vertical Fine Adjustment"), "Color=No,Category=Advanced Printer Setup",
    N_("Fine adjustment to horizontal position for CD printing"),
    STP_PARAMETER_TYPE_DIMENSION, STP_PARAMETER_CLASS_FEATURE,
    STP_PARAMETER_LEVEL_ADVANCED, 1, 1, STP_CHANNEL_NONE, 1, 0
  },
  {
    "Resolution", N_("Resolution"), "Color=Yes,Category=Basic Printer Setup",
    N_("Resolution and quality of the print"),
    STP_PARAMETER_TYPE_STRING_LIST, STP_PARAMETER_CLASS_FEATURE,
    STP_PARAMETER_LEVEL_BASIC, 1, 1, STP_CHANNEL_NONE, 1, 0
  },
  /*
   * Don't check this parameter.  We may offer different settings for
   * different ink sets, but we need to be able to handle settings from PPD
   * files that don't have constraints set up.
   */
  {
    "InkType", N_("Ink Type"), "Color=Yes,Category=Advanced Printer Setup",
    N_("Type of ink in the printer"),
    STP_PARAMETER_TYPE_STRING_LIST, STP_PARAMETER_CLASS_FEATURE,
    STP_PARAMETER_LEVEL_BASIC, 1, 1, STP_CHANNEL_NONE, 0, 0
  },
  {
    "InkChannels", N_("Ink Channels"), "Color=Yes,Category=Advanced Printer Functionality",
    N_("Ink Channels"),
    STP_PARAMETER_TYPE_INT, STP_PARAMETER_CLASS_FEATURE,
    STP_PARAMETER_LEVEL_INTERNAL, 0, 0, STP_CHANNEL_NONE, 0, 0
  },
  /*
   * Don't check this parameter.  We may offer different settings for
   * different ink sets, but we need to be able to handle settings from PPD
   * files that don't have constraints set up.
   */
  {
    "PrintingMode", N_("Printing Mode"), "Color=Yes,Category=Core Parameter",
    N_("Printing Output Mode"),
    STP_PARAMETER_TYPE_STRING_LIST, STP_PARAMETER_CLASS_CORE,
    STP_PARAMETER_LEVEL_BASIC, 1, 1, STP_CHANNEL_NONE, 0, 0
  },
  /*
   * Don't check this parameter.  We may offer different settings for
   * different ink sets, but we need to be able to handle settings from PPD
   * files that don't have constraints set up.
   */
  {
    "InkSet", N_("Ink Set"), "Color=Yes,Category=Basic Printer Setup",
    N_("Type of inkset in the printer"),
    STP_PARAMETER_TYPE_STRING_LIST, STP_PARAMETER_CLASS_FEATURE,
    STP_PARAMETER_LEVEL_BASIC, 1, 1, STP_CHANNEL_NONE, 0, 0
  },
  {
    "FullBleed", N_("Borderless"), "Color=No,Category=Basic Printer Setup",
    N_("Print without borders"),
    STP_PARAMETER_TYPE_BOOLEAN, STP_PARAMETER_CLASS_FEATURE,
    STP_PARAMETER_LEVEL_BASIC, 1, 1, STP_CHANNEL_NONE, 1, 0
  },
  {
    "Duplex", N_("Double-Sided Printing"), "Color=No,Category=Basic Printer Setup",
    N_("Duplex/Tumble Setting"),
    STP_PARAMETER_TYPE_STRING_LIST, STP_PARAMETER_CLASS_FEATURE,
    STP_PARAMETER_LEVEL_BASIC, 1, 1, STP_CHANNEL_NONE, 1, 0
  },
  {
    "Quality", N_("Print Quality"), "Color=Yes,Category=Basic Output Adjustment",
    N_("Print Quality"),
    STP_PARAMETER_TYPE_STRING_LIST, STP_PARAMETER_CLASS_FEATURE,
    STP_PARAMETER_LEVEL_BASIC, 1, 1, STP_CHANNEL_NONE, 0, 0
  },
};

static const int the_parameter_count =
sizeof(the_parameters) / sizeof(const stp_parameter_t);

typedef struct
{
  const stp_parameter_t param;
  double min;
  double max;
  double defval;
  int color_only;
} float_param_t;

static const float_param_t float_parameters[] =
{
  {
    {
      "CyanDensity", N_("Cyan Density"), "Color=Yes,Category=Output Level Adjustment",
      N_("Adjust the cyan density"),
      STP_PARAMETER_TYPE_DOUBLE, STP_PARAMETER_CLASS_OUTPUT,
      STP_PARAMETER_LEVEL_ADVANCED, 0, 1, 1, 1, 0
    }, 0.0, 2.0, 1.0, 1
  },
  {
    {
      "MagentaDensity", N_("Magenta Density"), "Color=Yes,Category=Output Level Adjustment",
      N_("Adjust the magenta density"),
      STP_PARAMETER_TYPE_DOUBLE, STP_PARAMETER_CLASS_OUTPUT,
      STP_PARAMETER_LEVEL_ADVANCED, 0, 1, 2, 1, 0
    }, 0.0, 2.0, 1.0, 1
  },
  {
    {
      "YellowDensity", N_("Yellow Density"), "Color=Yes,Category=Output Level Adjustment",
      N_("Adjust the yellow density"),
      STP_PARAMETER_TYPE_DOUBLE, STP_PARAMETER_CLASS_OUTPUT,
      STP_PARAMETER_LEVEL_ADVANCED, 0, 1, 3, 1, 0
    }, 0.0, 2.0, 1.0, 1
  },
  {
    {
      "BlackDensity", N_("Black Density"), "Color=Yes,Category=Output Level Adjustment",
      N_("Adjust the black density"),
      STP_PARAMETER_TYPE_DOUBLE, STP_PARAMETER_CLASS_OUTPUT,
      STP_PARAMETER_LEVEL_ADVANCED, 0, 1, 0, 1, 0
    }, 0.0, 2.0, 1.0, 1
  },
  {
    {
      "LightCyanTrans", N_("Light Cyan Transition"), "Color=Yes,Category=Advanced Ink Adjustment",
      N_("Light Cyan Transition"),
      STP_PARAMETER_TYPE_DOUBLE, STP_PARAMETER_CLASS_OUTPUT,
      STP_PARAMETER_LEVEL_ADVANCED4, 0, 1, STP_CHANNEL_NONE, 1, 0
    }, 0.0, 5.0, 1.0, 1
  },
  {
    {
      "LightMagentaTrans", N_("Light Magenta Transition"), "Color=Yes,Category=Advanced Ink Adjustment",
      N_("Light Magenta Transition"),
      STP_PARAMETER_TYPE_DOUBLE, STP_PARAMETER_CLASS_OUTPUT,
      STP_PARAMETER_LEVEL_ADVANCED4, 0, 1, STP_CHANNEL_NONE, 1, 0
    }, 0.0, 5.0, 1.0, 1
  },
 {
    {
      "LightYellowTrans", N_("Light Yellow Transition"), "Color=Yes,Category=Advanced Ink Adjustment",
      N_("Light Yellow Transition"),
      STP_PARAMETER_TYPE_DOUBLE, STP_PARAMETER_CLASS_OUTPUT,
      STP_PARAMETER_LEVEL_ADVANCED4, 0, 1, STP_CHANNEL_NONE, 1, 0
    }, 0.0, 5.0, 1.0, 1
  },
};

static const int float_parameter_count =
sizeof(float_parameters) / sizeof(const float_param_t);

/*
 * Duplex support - modes available
 * Note that the internal names MUST match those in cups/genppd.c else the
 * PPD files will not be generated correctly
 */

static const stp_param_string_t duplex_types[] =
{
  { "None",             N_ ("Off") },
  { "DuplexNoTumble",   N_ ("Long Edge (Standard)") },
  { "DuplexTumble",     N_ ("Short Edge (Flip)") }
};
#define NUM_DUPLEX (sizeof (duplex_types) / sizeof (stp_param_string_t))

static const canon_paper_t *
get_media_type(const canon_cap_t* caps,const char *name)
{
  int i;
  if (name && caps->paperlist)
    {
      for (i = 0; i < caps->paperlist->count; i++)
        {
	  /* translate paper_t.name */
	  if (!strcmp(name, caps->paperlist->papers[i].name))
	    return &(caps->paperlist->papers[i]);
        }
      return &(caps->paperlist->papers[0]);
    }
  return NULL;
}

static const char* canon_families[] = {
 "", /* the old BJC printers */
 "S",
 "i",
 "PIXMA iP",
 "PIXMA iX",
 "PIXMA MP",
 "PIXUS",
 "PIXMA Pro",
 "PIXMA MG",
 "PIXMA MX",
 "SELPHY DS",
 "PIXMA mini",
 "PIXMA E",
};

/* canon model ids look like the following
   FFMMMMMM
   FF: family is the offset in the canon_families struct
   MMMMMM: model nr
*/
static char* canon_get_printername(const stp_vars_t* v)
{
  unsigned int model = stp_get_model_id(v);
  unsigned int family = model / 1000000; 
  unsigned int nr = model - family * 1000000;
  char* name;
  size_t len;
  if(family >= sizeof(canon_families) / sizeof(canon_families[0])){
    stp_eprintf(v,"canon_get_printername: no family %i using default BJC\n", family);
    family = 0;
  }
  len = strlen(canon_families[family]) + 7; /* max model nr. + terminating 0 */
  name = stp_zalloc(len);
  snprintf(name,len,"%s%u",canon_families[family],nr);
  if (ERRPRINT)
    stp_eprintf(v,"canon_get_printername: current printer name: %s\n", name);
  return name;
}

static const canon_cap_t * canon_get_model_capabilities(const stp_vars_t*v)
{
  int i;
  char* name = canon_get_printername(v);
  int models= sizeof(canon_model_capabilities) / sizeof(canon_cap_t);
  for (i=0; i<models; i++) {
    if (!strcmp(canon_model_capabilities[i].name,name)) {
      stp_free(name);
      return &(canon_model_capabilities[i]);
    }
  }
  stp_eprintf(v,"canon: model %s not found in capabilities list=> using default\n",name);
  stp_free(name);
  return &(canon_model_capabilities[0]);
}

static const canon_slot_t *
canon_source_type(const char *name, const canon_cap_t * caps)
{
    if(name){
        int i;
        for(i=0; i<caps->slotlist->count; i++){
            if( !strcmp(name,caps->slotlist->slots[i].name))
                 return &(caps->slotlist->slots[i]);
        }
    }
    return &(caps->slotlist->slots[0]);
}

/* function returns the current set printmode (specified by resolution) */
/* if no mode is set the default mode will be returned */
static const canon_mode_t* canon_get_current_mode(const stp_vars_t *v){
#if 0
    const char* input_slot = stp_get_string_parameter(v, "InputSlot");
    const char *quality = stp_get_string_parameter(v, "Quality");
#endif
    const char *resolution = stp_get_string_parameter(v, "Resolution");
    const canon_cap_t * caps = canon_get_model_capabilities(v);
    const canon_mode_t* mode = NULL;
    const char *ink_type = stp_get_string_parameter(v, "InkType");/*debug*/
    const char *ink_set = stp_get_string_parameter(v, "InkSet");/*debug*/
    int i;

  stp_dprintf(STP_DBG_CANON, v,"Entered canon_get_current_mode\n");
  if (ERRPRINT)
    stp_eprintf(v,"entered canon_get_current_mode\n");

    if (ink_set)
      stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint: InkSet value (high priority): '%s'\n",ink_set);
    else
      stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint: InkSet value is NULL\n");
      
    if (ink_type)
      stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint: InkType value (low priority): '%s'\n",ink_type);
    else
      stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint: InkType value is NULL\n");

    if(resolution){
      for(i=0;i<caps->modelist->count;i++){
            if(!strcmp(resolution,caps->modelist->modes[i].name)){
                mode = &caps->modelist->modes[i];
                break;
            }
        }
    }
#if 0
    if(!mode)
        mode = &caps->modelist->modes[caps->modelist->default_mode];
#endif

#if 0
    if(quality && strcmp(quality, "None") == 0)
        quality = "Standard";

    if(quality && !strcmp(quality,"Standard")){
        return &caps->modelist->modes[caps->modelist->default_mode];
    }
#endif

#if 0
    /* only some modes can print to cd */
    if(input_slot && !strcmp(input_slot,"CD") && !(mode->flags & MODE_FLAG_CD)){
        for(i=0;i<caps->modelist->count;i++){
            if(caps->modelist->modes[i].flags & MODE_FLAG_CD){
                mode = &caps->modelist->modes[i];
                break;
            }
        }
    }
#endif

    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint: current mode is '%s'\n",resolution);
    if (ERRPRINT)
      stp_eprintf(v,"current mode is '%s'\n",resolution);
    
    return mode;
}

const canon_modeuse_t* select_media_modes(stp_vars_t *v, const canon_paper_t* media_type,const canon_modeuselist_t* mlist){
  const canon_modeuse_t* muse = NULL;
  int i;
  for(i=0;i<mlist->count;i++){
    if(!strcmp(media_type->name,mlist->modeuses[i].name)){
      muse = &mlist->modeuses[i];
      stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint: mode searching: assigned media '%s'\n",mlist->name);
      if (ERRPRINT)
	stp_eprintf(v,"mode searching: assigned media '%s'\n",mlist->name);
      break;
    }
  }
  return muse;
}

int compare_mode_valid(stp_vars_t *v,const canon_mode_t* mode,const canon_modeuse_t* muse, const canon_modeuselist_t* mlist){
  int i=0;
  int modecheck=1;
  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint: mode searching: assigned mode-media '%s'\n",mlist->name);
  if (ERRPRINT)
    stp_eprintf(v,"mode searching: assigned mode-media '%s'\n",mlist->name);
  while (muse->mode_name_list[i]!=NULL){
    if(!strcmp(mode->name,muse->mode_name_list[i])){
      modecheck=0;
      break;
    }
    i++;
  }
  return modecheck;
}

const canon_mode_t* suitable_mode_monochrome(stp_vars_t *v,const canon_modeuse_t* muse,const canon_cap_t *caps,int quality,const char *duplex_mode) {
  const canon_mode_t* mode=NULL;
  int i=0;
  int j;
  int modefound=0;

  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Entered suitable_mode_monochrome\n");

  while ((muse->mode_name_list[i]!=NULL) && (modefound != 1)){
    for(j=0;j<caps->modelist->count;j++){
      if(!strcmp(muse->mode_name_list[i],caps->modelist->modes[j].name)){/* find right place in canon-modes list */
	if ( (muse->use_flags & INKSET_BLACK_MODEREPL) ) { 
	  /* only look at modes with MODE_FLAG_BLACK if INKSET_BLACK_MODEREPL is in force */
	  if ( (caps->modelist->modes[j].quality >= quality) && (caps->modelist->modes[j].flags & MODE_FLAG_BLACK) ){ 
	    /* keep setting the mode until lowest matching quality is found */
	    if ( !(duplex_mode) || !(muse->use_flags & DUPLEX_SUPPORT) || !(caps->modelist->modes[j].flags & MODE_FLAG_NODUPLEX) ) {
	      /* duplex check -- rare for monochrome, cannot remember any such case */
	      mode = &caps->modelist->modes[j];
	      modefound=1;
	    }
	  }
	  break; /* go to next mode in muse list */
	}
	else { /* no special replacement modes for black inkset */
	  if ( (caps->modelist->modes[j].quality >= quality) ){ 
	    /* keep setting the mode until lowest matching quality is found */
	    if ( !(duplex_mode) || !(muse->use_flags & DUPLEX_SUPPORT) || !(caps->modelist->modes[j].flags & MODE_FLAG_NODUPLEX) ) {
	      /* duplex check -- rare for monochrome, cannot remember any such case */
	      mode = &caps->modelist->modes[j];
	      modefound=1;
	    }
	  }
	  break; /* go to next mode in muse list */
	}
      }
    }
    i++;
  }
  return mode;
}

const canon_mode_t* find_first_matching_mode_monochrome(stp_vars_t *v,const canon_modeuse_t* muse,const canon_cap_t *caps,const char *duplex_mode) {
  const canon_mode_t* mode=NULL;
  /* only look at modes with MODE_FLAG_BLACK if INKSET_BLACK_MODEREPL is in force */
  int i=0;
  int modefound=0;
  int j;

  while ( (muse->mode_name_list[i]!=NULL)  && (modefound != 1) ) {
    /* pick first mode with MODE_FLAG_BLACK */
    for(j=0;j<caps->modelist->count;j++){
      if(!strcmp(muse->mode_name_list[i],caps->modelist->modes[j].name)){/* find right place in canon-modes list */
	/* only look at modes with MODE_FLAG_BLACK if INKSET_BLACK_MODEREPL is in force */
	if ( (caps->modelist->modes[j].flags & MODE_FLAG_BLACK) ) { 
	  if ( !(duplex_mode) || !(muse->use_flags & DUPLEX_SUPPORT) || !(caps->modelist->modes[j].flags & MODE_FLAG_NODUPLEX) ) {
	    /* duplex check -- rare for monochrome, cannot remember any such case */
	    mode = &caps->modelist->modes[j];
	    modefound=1;
	  }
	}
	break; /* go to next mode in muse list */
      }
    }
    i++;
  }
  return mode;
}

const canon_mode_t* find_first_matching_mode(stp_vars_t *v,const canon_modeuse_t* muse,const canon_cap_t *caps,const char *duplex_mode) {
  const canon_mode_t* mode=NULL;
  int i=0;
  int modefound=0;
  int j;

  while ( (muse->mode_name_list[i]!=NULL)  && (modefound != 1) ) {
    for(j=0;j<caps->modelist->count;j++){
      if(!strcmp(muse->mode_name_list[i],caps->modelist->modes[j].name)){/* find right place in canon-modes list */
	if ( !(duplex_mode) || !(muse->use_flags & DUPLEX_SUPPORT) || !(caps->modelist->modes[j].flags & MODE_FLAG_NODUPLEX) ) {
	  /* duplex check -- rare for monochrome, cannot remember any such case */
	  mode = &caps->modelist->modes[j];
	  modefound=1;
	  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (find_first_matching_mode): picked mode without inkset limitation (%s)\n",mode->name);
	}
	break; /* go to next mode in muse list */
      }
    }
    i++;
  }
  return mode;
}

const canon_mode_t* suitable_mode_color(stp_vars_t *v,const canon_modeuse_t* muse,const canon_cap_t *caps,int quality,const char *duplex_mode) {
  const canon_mode_t* mode=NULL;
  int i=0;
  int j;
  int modefound=0;
  
  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Entered suitable_mode_color\n");

  while ((muse->mode_name_list[i]!=NULL) && (modefound != 1)){
    for(j=0;j<caps->modelist->count;j++){
      if(!strcmp(muse->mode_name_list[i],caps->modelist->modes[j].name)){/* find right place in canon-modes list */
	if ( (muse->use_flags & INKSET_COLOR_MODEREPL) ) { 
	  /* only look at modes with MODE_FLAG_COLOR if INKSET_COLOR_MODEREPL is in force */
	  if ( (caps->modelist->modes[j].quality >= quality)  && (caps->modelist->modes[j].flags & MODE_FLAG_COLOR) ) { 
	    /* keep setting the mode until lowest matching quality is found */
	    if ( !(duplex_mode) || !(muse->use_flags & DUPLEX_SUPPORT) || !(caps->modelist->modes[j].flags & MODE_FLAG_NODUPLEX) ) {
	      /* duplex check */
	      mode = &caps->modelist->modes[j];
	      stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (suitable_mode_color): picked mode with special replacement inkset (%s)\n",mode->name);
	      modefound=1;
	    }
	  }
	  break; /* go to next mode in muse list */
	}
	else { /* no special replacement modes for color inkset */
	  if ( (caps->modelist->modes[j].quality >= quality) ){ 
	    /* keep setting the mode until lowest matching quality is found */
	    if ( !(duplex_mode) || !(muse->use_flags & DUPLEX_SUPPORT) || !(caps->modelist->modes[j].flags & MODE_FLAG_NODUPLEX) ) {
	      /* duplex check */
	      mode = &caps->modelist->modes[j];
	      stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (suitable_mode_color): picked mode without any special replacement inkset (%s)\n",mode->name);
	      modefound=1;
	    }
	  }
	  break; /* go to next mode in muse list */
	}
      }
    }
    i++;
  }
  return mode;
}

const canon_mode_t* find_first_matching_mode_color(stp_vars_t *v,const canon_modeuse_t* muse,const canon_cap_t *caps,const char *duplex_mode) {
  const canon_mode_t* mode=NULL;
  /* only look at modes with MODE_FLAG_COLOR if INKSET_COLOR_MODEREPL is in force */
  int i=0;
  int modefound=0;
  int j;

  while ( (muse->mode_name_list[i]!=NULL)  && (modefound != 1) ) {
    /* pick first mode with MODE_FLAG_COLOR */
    for(j=0;j<caps->modelist->count;j++){
      if(!strcmp(muse->mode_name_list[i],caps->modelist->modes[j].name)){/* find right place in canon-modes list */
	/* only look at modes with MODE_FLAG_COLOR if INKSET_COLOR_MODEREPL is in force */
	if ( (caps->modelist->modes[j].flags & MODE_FLAG_COLOR) ) { 
	  if ( !(duplex_mode) || !(muse->use_flags & DUPLEX_SUPPORT) || !(caps->modelist->modes[j].flags & MODE_FLAG_NODUPLEX) ) {
	    /* duplex check */
	    mode = &caps->modelist->modes[j];
	    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (find_first_matching_mode_color): picked first mode with special replacement inkset (%s)\n",mode->name);
	    modefound=1;
	  }
	}
	break; /* go to next mode in muse list */
      }
    }
    i++;
  }
  return mode;
}

const canon_mode_t* suitable_mode_photo(stp_vars_t *v,const canon_modeuse_t* muse,const canon_cap_t *caps,int quality,const char *duplex_mode) {
  const canon_mode_t* mode=NULL;
  int i=0;
  int j;
  int modefound=0;

  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Entered suitable_mode_photo\n");
  
  while ((muse->mode_name_list[i]!=NULL) && (modefound != 1)){
    for(j=0;j<caps->modelist->count;j++){
      if(!strcmp(muse->mode_name_list[i],caps->modelist->modes[j].name)){/* find right place in canon-modes list */
	if ( (muse->use_flags & INKSET_PHOTO_MODEREPL) ) { 
	  /* only look at modes with MODE_FLAG_PHOTO if INKSET_PHOTO_MODEREPL is in force */
	  if ( (caps->modelist->modes[j].quality >= quality)  && (caps->modelist->modes[j].flags & MODE_FLAG_PHOTO) ) { 
	    /* keep setting the mode until lowest matching quality is found */
	    if ( !(duplex_mode) || !(muse->use_flags & DUPLEX_SUPPORT) || !(caps->modelist->modes[j].flags & MODE_FLAG_NODUPLEX) ) {
	      /* duplex check */
	      mode = &caps->modelist->modes[j];
	      modefound=1;
	    }
	  }
	  break; /* go to next mode in muse list */
	}
	else { /* if no special replacement modes for photo inkset */
	  if ( (caps->modelist->modes[j].quality >= quality) ){ 
	    /* keep setting the mode until lowest matching quality is found */
	    if ( !(duplex_mode) || !(muse->use_flags & DUPLEX_SUPPORT) || !(caps->modelist->modes[j].flags & MODE_FLAG_NODUPLEX) ) {
	      /* duplex check */
	      mode = &caps->modelist->modes[j];
	      modefound=1;
	    }
	  }
	  break; /* go to next mode in muse list */
	}
      }
    }
    i++;
  }
  return mode;
}

const canon_mode_t* find_first_matching_mode_photo(stp_vars_t *v,const canon_modeuse_t* muse,const canon_cap_t *caps,const char *duplex_mode) {
  const canon_mode_t* mode=NULL;
  /* only look at modes with MODE_FLAG_PHOTO if INKSET_PHOTO_MODEREPL is in force */
  int i=0;
  int modefound=0;
  int j;
  
  while ( (muse->mode_name_list[i]!=NULL)  && (modefound != 1) ) {
    /* pick first mode with MODE_FLAG_PHOTO */
    for(j=0;j<caps->modelist->count;j++){
      if(!strcmp(muse->mode_name_list[i],caps->modelist->modes[j].name)){/* find right place in canon-modes list */
	/* only look at modes with MODE_FLAG_PHOTO if INKSET_PHOTO_MODEREPL is in force */
	if ( (caps->modelist->modes[j].flags & MODE_FLAG_PHOTO) ) { 
	  if ( !(duplex_mode) || !(muse->use_flags & DUPLEX_SUPPORT) || !(caps->modelist->modes[j].flags & MODE_FLAG_NODUPLEX) ) {
	    /* duplex check */
	    mode = &caps->modelist->modes[j];
	    modefound=1;
	  }
	}
	break; /* go to next mode in muse list */
      }
    }
    i++;
  }
  return mode;
}

const canon_mode_t* suitable_mode_general(stp_vars_t *v,const canon_modeuse_t* muse,const canon_cap_t *caps,int quality,const char *duplex_mode) {
  const canon_mode_t* mode=NULL;
  int i=0;
  int j;
  int modefound=0;

  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Entered suitable_mode_general\n");
  
  while ((muse->mode_name_list[i]!=NULL) && (modefound != 1)){
    for(j=0;j<caps->modelist->count;j++){
      if(!strcmp(muse->mode_name_list[i],caps->modelist->modes[j].name)){/* find right place in canon-modes list */
	if ( (caps->modelist->modes[j].quality >= quality) ) { 
	  /* keep setting the mode until lowest matching quality is found */
	  if ( !(duplex_mode) || !(muse->use_flags & DUPLEX_SUPPORT) || !(caps->modelist->modes[j].flags & MODE_FLAG_NODUPLEX) ) {
	    /* duplex check */
	    mode = &caps->modelist->modes[j];
	    modefound=1;
	  }
	}
	break; /* go to next mode in muse list */
      }
    }
    i++;
  }
  return mode;
}

const char* find_ink_type(stp_vars_t *v,const canon_mode_t* mode,const char *printing_mode) {
  int i,inkfound;
  const char *ink_type = stp_get_string_parameter(v, "InkType");

  /* if InkType does not match that of mode, change InkType to match it */
  /* choose highest color as default, as there is only one option for Black */
  /* if InkType does not match that of mode, change InkType to match it */
  /* choose highest color as default, as there is only one option for Black */
  if (printing_mode && !strcmp(printing_mode,"BW")) {
    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType changed to %u (%s)\n",CANON_INK_K, "Gray");
    stp_set_string_parameter(v, "InkType", "Gray");
    ink_type = stp_get_string_parameter(v, "InkType");
  } else {
    inkfound=0;
    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType of mode %s is currently set as %s\n",mode->name,ink_type);
    for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
      if (mode->ink_types & canon_inktypes[i].ink_type) { /* a mode can have several ink_types: must compare with ink_type if set */
	if ( !(strcmp(ink_type,canon_inktypes[i].name))) {
	  inkfound=1;
	  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType match found %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
	  stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
	  ink_type = stp_get_string_parameter(v, "InkType");
	  break;
	}
      }
    }
    /* if no match found choose first available inkset */
    if (inkfound==0) {
      for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	if (mode->ink_types & canon_inktypes[i].ink_type) { /* a mode can have several ink_types: must compare with ink_type if set */
	  if ((!ink_type) || (strcmp(ink_type,canon_inktypes[i].name))) { /* if InkType does not match selected mode ink type*/
	    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): No match found---InkType changed to %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
	    stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
	    ink_type = stp_get_string_parameter(v, "InkType");
	    inkfound=1; /* set */
	    break;
	  }
	}
      }
    }
  }
  return ink_type;
}

/* function checks printmode (specified by resolution) */
/* and substitutes a mode if needed. NULL is returned for now */
const canon_mode_t* canon_check_current_mode(stp_vars_t *v){
#if 0
  const char* input_slot = stp_get_string_parameter(v, "InputSlot");
  const char *quality = stp_get_string_parameter(v, "Quality");
#endif
  const char *resolution = stp_get_string_parameter(v, "Resolution");
  const char *ink_set = stp_get_string_parameter(v, "InkSet");
  const char *duplex_mode = stp_get_string_parameter(v, "Duplex");
  const char *ink_type = stp_get_string_parameter(v, "InkType");
  const char *printing_mode = stp_get_string_parameter(v, "PrintingMode");
  const canon_cap_t * caps = canon_get_model_capabilities(v);
  const canon_mode_t* mode = NULL;
  const canon_modeuselist_t* mlist = caps->modeuselist;
  const canon_modeuse_t* muse = NULL;
  const canon_paper_t* media_type = get_media_type(caps,stp_get_string_parameter(v, "MediaType"));
  int i,j;
  int modecheck, quality, modefound;
#if 0
  int inkfound;
#endif

  stp_dprintf(STP_DBG_CANON, v,"Entered canon_check_current_mode: got PrintingMode %s\n",printing_mode);
  if (ERRPRINT)
    stp_eprintf(v,"entered canon_check_current_mode: got PrintingMode %s\n",printing_mode);

  /* Logic: priority of options
     1. Media --- always present for final selection.
     2. InkSet (cartridge selection) --- optional as only some printers offer this.
     3. PrintingMode --- for printers which have K-only monochrome modes can choose BW.
     4. Duplex --- for printers that have special duplex modes need to skip non-duplex modes.
     5. InkType --- suggestion only, since modes are tied to ink types in most Canon printers.
     6. Quality --- suggestion, based on initially-selected mode.
     7. Mode --- once chosen, InkType is selected based on quality, inkset, printing mode.
  */

  /*
    canon-mode-media:
    INKSET_BLACK_SUPPORT: media type supports black-only cartridge
    INKSET_COLOR_SUPPORT: media type supports color-only cartridge
    INKSET_BLACK_MODEREPL: media type has special modes for black-only cartridge
    INKSET_COLOR_MODEREPL: media type has special modes for black-only cartridge
    INKSET_PHOTO_SUPPORT: media type supports special photo cartridge
    DUPLEX_MODEREPL: media type has (a) special mode(s) for duplex
    canon-modes.h:
    MODE_FLAG_BLACK: mode can be used for supporting black-only cartridge
    MODE_FLAG_COLOR: mode can be used for supporting color-only cartridge
    MODE_FLAG_PHOTO: mode can be used for supporting photo cartridge
    MODE_FLAG_NOPDUPLEX: mode cannot be used for duplex, must be skipped
  */

  if(resolution){
    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint:  check_current_mode --- (Initial) Resolution already known: '%s'\n",resolution);
    if (ERRPRINT)
      stp_eprintf(v,"check_current_mode --- (Initial) Resolution already known: '%s'\n",resolution);
    for(i=0;i<caps->modelist->count;i++){
      if(!strcmp(resolution,caps->modelist->modes[i].name)){
	mode = &caps->modelist->modes[i];
	break;
      }
    }
  }
  else {
    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint:  check_current_mode --- (Initial) Resolution not yet known \n");
    if (ERRPRINT)
      stp_eprintf(v,"check_current_mode --- (Initial) Resolution not yet known \n");
  }
    
  if (ink_set)
    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint: (Initial) InkSet value (high priority): '%s'\n",ink_set);
  else
    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint: (Initial) InkSet value is NULL\n");
  
  if (ink_type)
    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint: (Initial) InkType value (low priority): '%s'\n",ink_type);
  else
    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint: (Initial) InkType value is NULL\n");

  /* beginning of mode replacement code */
  if (media_type && resolution && mode) {
    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint:  check_current_mode --- Resolution, Media, Mode all known \n");
    if (ERRPRINT)
      stp_eprintf(v,"check_current_mode --- Resolution, Media, Mode all known \n");
    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint: media type selected: '%s'\n",media_type->name);
    if (ERRPRINT)
      stp_eprintf(v,"media type selected: '%s'\n",media_type->name);
    stp_dprintf(STP_DBG_CANON, v,"DEBUG: (Inital) Gutenprint: mode initally active: '%s'\n",mode->name);
    if (ERRPRINT)
      stp_eprintf(v,"(Inital) mode initially active: '%s'\n",mode->name);
      
    /* scroll through modeuse list to find media */
    muse = select_media_modes(v,media_type,mlist);

    /* now scroll through to find if the mode is in the modeuses list */
    modecheck=compare_mode_valid(v,mode,muse,mlist);

    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint: modecheck value: '%i'\n",modecheck);
    if (ERRPRINT)
      stp_eprintf(v,"modecheck value: '%i'\n",modecheck);
            
    /* if we did not find a valid mode, need to replace it */
    if (modecheck!=0) {

      stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (check_current_mode): no suitable mode exists, need to find a mode\n");
      quality = mode->quality;
      /* Black InkSet */
      if (ink_set && !strcmp(ink_set,"Black"))  {
	stp_set_string_parameter(v, "PrintingMode","BW");
	printing_mode = stp_get_string_parameter(v, "PrintingMode");
	if (!(mode->ink_types & CANON_INK_K)) {
	  /* need a new mode: 
	     loop through modes in muse list searching for a matching inktype, comparing quality
	  */
	  mode=suitable_mode_monochrome(v,muse,caps,quality,duplex_mode);
	  if (!mode)
	    modefound=0;
	  else
	    modefound=1;

	  if (modefound == 0) { /* still did not find a mode: pick first one for that media matching the InkSet limitation */
	    if ( (muse->use_flags & INKSET_BLACK_MODEREPL) ) {  
	      mode=find_first_matching_mode_monochrome(v,muse,caps,duplex_mode);
	    }
	    else {  /* no special replacement modes for black inkset */
	      mode=find_first_matching_mode(v,muse,caps,duplex_mode);
	    }
	  }
	  if (!mode)
	    modefound=0;
	  else
	    modefound=1;

	  /* set InkType for the mode found */
	  for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	    if (mode->ink_types & canon_inktypes[i].ink_type) {
	      if (strcmp(ink_type,canon_inktypes[i].name)) { /* if InkType does not match selected mode ink type*/
		stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Black): InkType changed to %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		ink_type = stp_get_string_parameter(v, "InkType");
		break;
	      }
	    }
	  }
	}
	else {
	  /* mode is fine */
	  /* matched expected K inkset, but need to check if Duplex matches, and if not, get a new mode with right inkset */
	  mode=suitable_mode_monochrome(v,muse,caps,quality,duplex_mode);
	  if (!mode)
	    modefound=0;
	  else
	    modefound=1;

	  if (modefound == 0) { /* still did not find a mode: pick first one for that media matching the InkSet limitation */
	    if ( (muse->use_flags & INKSET_BLACK_MODEREPL) ) {
	    mode=find_first_matching_mode_monochrome(v,muse,caps,duplex_mode);
	    }
	    else {  /* no special replacement modes for black inkset */
	      mode=find_first_matching_mode(v,muse,caps,duplex_mode);
	    }
	  }

	  ink_type=find_ink_type(v,mode,printing_mode);
#if 0
	  /* if InkType does not match that of mode, change InkType to match it */
	  /* choose highest color as default, as there is only one option for Black */
	  /* if InkType does not match that of mode, change InkType to match it */
	  /* choose highest color as default, as there is only one option for Black */
	  if (printing_mode && !strcmp(printing_mode,"BW")) {
	    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType changed to %u (%s)\n",CANON_INK_K, "Gray");
	    stp_set_string_parameter(v, "InkType", "Gray");
	    ink_type = stp_get_string_parameter(v, "InkType");
	  } else {
	    inkfound=0;
	    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType of mode %s is currently set as %s\n",mode->name,ink_type);
	    for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	      if (mode->ink_types & canon_inktypes[i].ink_type) { /* a mode can have several ink_types: must compare with ink_type if set */
		if ( !(strcmp(ink_type,canon_inktypes[i].name))) {
		  inkfound=1;
		  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType match found %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		  stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		  ink_type = stp_get_string_parameter(v, "InkType");
		  break;
		}
	      }
	    }
	    /* if no match found choose first available inkset */
	    if (inkfound==0) {
	      for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
		if (mode->ink_types & canon_inktypes[i].ink_type) { /* a mode can have several ink_types: must compare with ink_type if set */
		  if ((!ink_type) || (strcmp(ink_type,canon_inktypes[i].name))) { /* if InkType does not match selected mode ink type*/
		    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): No match found---InkType changed to %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		    stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		    ink_type = stp_get_string_parameter(v, "InkType");
		    inkfound=1; /* set */
		    break;
		  }
		}
	      }
	    }
	  }
#endif
	  
#if 0
	  /* set InkType for the mode found */
	  for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	    if (mode->ink_types & canon_inktypes[i].ink_type) {
	      if (strcmp(ink_type,canon_inktypes[i].name)) { /* if InkType does not match selected mode ink type*/
		stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Black): InkType changed to %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		ink_type = stp_get_string_parameter(v, "InkType");
		break;
	      }
	    }
	  }
#endif

	}
      } /* End of Black Inkset */
      /*-------------------------------------------------------------------------------------------------*/
      /* Color InkSet */
      /* Added limitation: "Color" for BJC corresponds to "Both" on other types */
      else if ( (ink_set && !strcmp(ink_set,"Color")) && (caps->features & CANON_CAP_T) ) {
	stp_set_string_parameter(v, "PrintingMode","Color");
	printing_mode = stp_get_string_parameter(v, "PrintingMode");
	if (!(mode->ink_types & CANON_INK_CMY)) {
	  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Color): inkset incorrect for Color cartridge---need new mode\n");
	  /* need a new mode
	     loop through modes in muse list searching for a matching inktype, comparing quality
	  */
	  mode=suitable_mode_color(v,muse,caps,quality,duplex_mode);
	  if (!mode)
	    modefound=0;
	  else
	    modefound=1;

	  if (modefound == 0) { /* still did not find a mode: pick first one for that media */
	    if ( (muse->use_flags & INKSET_COLOR_MODEREPL) ) {  
	      mode=find_first_matching_mode_color(v,muse,caps,duplex_mode);
	      stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Color): Decided on first matching mode for color inkset (%s)\n",mode->name);
	    }
	    else {  /* no special replacement modes for color inkset */
	      mode=find_first_matching_mode(v,muse,caps,duplex_mode);
	      stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Color): Decided on first matching mode with no special replacement modes for color inkset (%s)\n",mode->name);
	    }
	  }
	  if (!mode)
	    modefound=0;
	  else
	    modefound=1;

	  ink_type=find_ink_type(v,mode,printing_mode);
#if 0
	  /* if InkType does not match that of mode, change InkType to match it */
	  /* choose highest color as default, as there is only one option for Black */
	  /* if InkType does not match that of mode, change InkType to match it */
	  /* choose highest color as default, as there is only one option for Black */
	  if (printing_mode && !strcmp(printing_mode,"BW")) {
	    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType changed to %u (%s)\n",CANON_INK_K, "Gray");
	    stp_set_string_parameter(v, "InkType", "Gray");
	    ink_type = stp_get_string_parameter(v, "InkType");
	  } else {
	    inkfound=0;
	    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType of mode %s is currently set as %s\n",mode->name,ink_type);
	    for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	      if (mode->ink_types & canon_inktypes[i].ink_type) { /* a mode can have several ink_types: must compare with ink_type if set */
		if ( !(strcmp(ink_type,canon_inktypes[i].name))) {
		  inkfound=1;
		  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType match found %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		  stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		  ink_type = stp_get_string_parameter(v, "InkType");
		  break;
		}
	      }
	    }
	    /* if no match found choose first available inkset */
	    if (inkfound==0) {
	      for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
		if (mode->ink_types & canon_inktypes[i].ink_type) { /* a mode can have several ink_types: must compare with ink_type if set */
		  if ((!ink_type) || (strcmp(ink_type,canon_inktypes[i].name))) { /* if InkType does not match selected mode ink type*/
		    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): No match found---InkType changed to %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		    stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		    ink_type = stp_get_string_parameter(v, "InkType");
		    inkfound=1; /* set */
		    break;
		  }
		}
	      }
	    }
	  }
#endif	  
#if 0
	  /* set InkType for the mode found */
	  for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	    if (mode->ink_types & canon_inktypes[i].ink_type) {
	      if (strcmp(ink_type,canon_inktypes[i].name)) { /* if InkType does not match selected mode ink type*/
		stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Color): InkType changed to %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		ink_type = stp_get_string_parameter(v, "InkType");
		break;
	      }
	    }
	  }
#endif

	}
	else {
	  /* mode is fine */
	  /* matched expected RGB inkset, but need to check if Duplex matches, and if not, get a new mode with right inkset */
	  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Color): inkset OK but need to check other parameters\n");
	  mode=suitable_mode_color(v,muse,caps,quality,duplex_mode);
	  if (!mode)
	    modefound=0;
	  else
	    modefound=1;

	  if (modefound == 0) { /* still did not find a mode: pick first one for that media */
	    if ( (muse->use_flags & INKSET_COLOR_MODEREPL) ) {
	      mode=find_first_matching_mode_color(v,muse,caps,duplex_mode);
	      stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Color): Decided on first matching mode for color inkset (%s)\n",mode->name);
	    }
	    else {  /* no special replacement modes for color inkset */
	      mode=find_first_matching_mode(v,muse,caps,duplex_mode);
	      stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Color): Decided on first matching mode with no special replacement modes for color inkset (%s)\n",mode->name);
	    }
	  }
	  if (!mode)
	    modefound=0;
	  else
	    modefound=1;

	  ink_type=find_ink_type(v,mode,printing_mode);
#if 0
	  /* if InkType does not match that of mode, change InkType to match it */
	  /* choose highest color as default, as there is only one option for Black */
	  /* if InkType does not match that of mode, change InkType to match it */
	  /* choose highest color as default, as there is only one option for Black */
	  if (printing_mode && !strcmp(printing_mode,"BW")) {
	    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType changed to %u (%s)\n",CANON_INK_K, "Gray");
	    stp_set_string_parameter(v, "InkType", "Gray");
	    ink_type = stp_get_string_parameter(v, "InkType");
	  } else {
	    inkfound=0;
	    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType of mode %s is currently set as %s\n",mode->name,ink_type);
	    for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	      if (mode->ink_types & canon_inktypes[i].ink_type) { /* a mode can have several ink_types: must compare with ink_type if set */
		if ( !(strcmp(ink_type,canon_inktypes[i].name))) {
		  inkfound=1;
		  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType match found %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		  stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		  ink_type = stp_get_string_parameter(v, "InkType");
		  break;
		}
	      }
	    }
	    /* if no match found choose first available inkset */
	    if (inkfound==0) {
	      for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
		if (mode->ink_types & canon_inktypes[i].ink_type) { /* a mode can have several ink_types: must compare with ink_type if set */
		  if ((!ink_type) || (strcmp(ink_type,canon_inktypes[i].name))) { /* if InkType does not match selected mode ink type*/
		    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): No match found---InkType changed to %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		    stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		    ink_type = stp_get_string_parameter(v, "InkType");
		    inkfound=1; /* set */
		    break;
		  }
		}
	      }
	    }
	  }
#endif	  
#if 0
	  /* set InkType for the mode found */
	  for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	    if (mode->ink_types & canon_inktypes[i].ink_type) {
	      if (strcmp(ink_type,canon_inktypes[i].name)) { /* if InkType does not match selected mode ink type*/
		stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Color): InkType changed to %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		ink_type = stp_get_string_parameter(v, "InkType");
		break;
	      }
	    }
	  }
#endif

	}
      }  /* end of Color InkSet */
      /*-------------------------------------------------------------------------------------------------*/
      /* Photo cartridge selection: only use modes that support it */
      else if (ink_set && !strcmp(ink_set,"Photo")) {
	/* Photo cartridge printing does not seem to have any monochrome option */
	stp_set_string_parameter(v, "PrintingMode","Color");
	printing_mode = stp_get_string_parameter(v, "PrintingMode");
	/* need to match photo cartridge mode flag */
	if (!(mode->flags & MODE_FLAG_PHOTO)) {
	  /* need a new mode
	     loop through modes in muse list searching for a matching inkset, comparing quality
	  */
	  mode=suitable_mode_photo(v,muse,caps,quality,duplex_mode);
	  if (!mode)
	    modefound=0;
	  else
	    modefound=1;

	  if (modefound == 0) { /* still did not find a mode: pick first one for that media */
	    if ( (muse->use_flags & INKSET_PHOTO_MODEREPL) ) {
	      mode=find_first_matching_mode_photo(v,muse,caps,duplex_mode);
	    }
	    else {  /* no special replacement modes for photo inkset */
	      mode=find_first_matching_mode(v,muse,caps,duplex_mode);
	    }
	  }
	  if (!mode)
	    modefound=0;
	  else
	    modefound=1;

	  ink_type=find_ink_type(v,mode,printing_mode);
#if 0
	  /* if InkType does not match that of mode, change InkType to match it */
	  /* choose highest color as default, as there is only one option for Black */
	  /* if InkType does not match that of mode, change InkType to match it */
	  /* choose highest color as default, as there is only one option for Black */
	  if (printing_mode && !strcmp(printing_mode,"BW")) {
	    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType changed to %u (%s)\n",CANON_INK_K, "Gray");
	    stp_set_string_parameter(v, "InkType", "Gray");
	    ink_type = stp_get_string_parameter(v, "InkType");
	  } else {
	    inkfound=0;
	    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType of mode %s is currently set as %s\n",mode->name,ink_type);
	    for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	      if (mode->ink_types & canon_inktypes[i].ink_type) { /* a mode can have several ink_types: must compare with ink_type if set */
		if ( !(strcmp(ink_type,canon_inktypes[i].name))) {
		  inkfound=1;
		  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType match found %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		  stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		  ink_type = stp_get_string_parameter(v, "InkType");
		  break;
		}
	      }
	    }
	    /* if no match found choose first available inkset */
	    if (inkfound==0) {
	      for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
		if (mode->ink_types & canon_inktypes[i].ink_type) { /* a mode can have several ink_types: must compare with ink_type if set */
		  if ((!ink_type) || (strcmp(ink_type,canon_inktypes[i].name))) { /* if InkType does not match selected mode ink type*/
		    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): No match found---InkType changed to %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		    stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		    ink_type = stp_get_string_parameter(v, "InkType");
		    inkfound=1; /* set */
		    break;
		  }
		}
	      }
	    }
	  }
#endif
#if 0
	  /* set InkType for the mode found */
	  for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	    if (mode->ink_types & canon_inktypes[i].ink_type) {
	      if (strcmp(ink_type,canon_inktypes[i].name)) { /* if InkType does not match selected mode ink type*/
		stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Color): InkType changed to %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		ink_type = stp_get_string_parameter(v, "InkType");
		break;
	      }
	    }
	  }
#endif

	}
	else {
	  /* mode is fine */
	  /* matched expected inkset, but need to check if Duplex matches, and if not, get a new mode with right inkset */
	  mode=suitable_mode_photo(v,muse,caps,quality,duplex_mode);
	  if (!mode)
	    modefound=0;
	  else
	    modefound=1;

	  if (modefound == 0) { /* still did not find a mode: pick first one for that media */
	    if ( (muse->use_flags & INKSET_PHOTO_MODEREPL) ) {
	      mode=find_first_matching_mode_photo(v,muse,caps,duplex_mode);
	    }
	    else {  /* no special replacement modes for photo inkset */
	      mode=find_first_matching_mode(v,muse,caps,duplex_mode);
	    }
	  }
	  if (!mode)
	    modefound=0;
	  else
	    modefound=1;

	  ink_type=find_ink_type(v,mode,printing_mode);
#if 0
	  /* if InkType does not match that of mode, change InkType to match it */
	  /* choose highest color as default, as there is only one option for Black */
	  /* if InkType does not match that of mode, change InkType to match it */
	  /* choose highest color as default, as there is only one option for Black */
	  if (printing_mode && !strcmp(printing_mode,"BW")) {
	    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType changed to %u (%s)\n",CANON_INK_K, "Gray");
	    stp_set_string_parameter(v, "InkType", "Gray");
	    ink_type = stp_get_string_parameter(v, "InkType");
	  } else {
	    inkfound=0;
	    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType of mode %s is currently set as %s\n",mode->name,ink_type);
	    for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	      if (mode->ink_types & canon_inktypes[i].ink_type) { /* a mode can have several ink_types: must compare with ink_type if set */
		if ( !(strcmp(ink_type,canon_inktypes[i].name))) {
		  inkfound=1;
		  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType match found %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		  stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		  ink_type = stp_get_string_parameter(v, "InkType");
		  break;
		}
	      }
	    }
	    /* if no match found choose first available inkset */
	    if (inkfound==0) {
	      for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
		if (mode->ink_types & canon_inktypes[i].ink_type) { /* a mode can have several ink_types: must compare with ink_type if set */
		  if ((!ink_type) || (strcmp(ink_type,canon_inktypes[i].name))) { /* if InkType does not match selected mode ink type*/
		    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): No match found---InkType changed to %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		    stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		    ink_type = stp_get_string_parameter(v, "InkType");
		    inkfound=1; /* set */
		    break;
		  }
		}
	      }
	    }
	  }
#endif	  
#if 0
	  /* set InkType for the mode found */
	  for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	    if (mode->ink_types & canon_inktypes[i].ink_type) {
	      if (strcmp(ink_type,canon_inktypes[i].name)) { /* if InkType does not match selected mode ink type*/
		stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Color): InkType changed to %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		ink_type = stp_get_string_parameter(v, "InkType");
		break;
	      }
	    }
	  }

#endif

	} 
      } /* end of Photo Inkset  */
      /*-------------------------------------------------------------------------------------------------*/
      /* no restrictions for InkSet "Both" (non-BJC) or "Color" (BJC) or if no InkSet set yet --- do not worry about InkSet at all */
      else {
	if (printing_mode && !strcmp(printing_mode,"Color")) {
	  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both) PrintingMode Color\n");
	  /* must skip K-only inksets if they exist: they only exist if the option "BW" is also declared but we cannot check if an option exists or not */
	  /*if ( (duplex_mode) || (mode->flags & MODE_FLAG_NODUPLEX) ) {*/
	  i=0;
	  quality = mode->quality;
	  modefound=0;
	  while ( (muse->mode_name_list[i]!=NULL)  && (modefound != 1) ) {
	    for(j=0;j<caps->modelist->count;j++){
	      if(!strcmp(muse->mode_name_list[i],caps->modelist->modes[j].name)){/* find right place in canon-modes list */
		if ( (caps->modelist->modes[j].quality >= quality) ) {
		  if ( !(duplex_mode) || !(muse->use_flags & DUPLEX_SUPPORT) || !(caps->modelist->modes[j].flags & MODE_FLAG_NODUPLEX) ) {
		    /* duplex check */
		    if (caps->modelist->modes[j].ink_types > CANON_INK_K) {
		      mode = &caps->modelist->modes[j];
		      modefound=1;
		    }
		  }
		}
		break; /* go to next mode in muse list */
	      }
	    }
	    i++;
	  }
	  /*}*/
	}
	else if (printing_mode && !strcmp(printing_mode,"BW")) {
	  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both) PrintingMode BW\n");
	  /* need to find K-only inksets: they must exist since we declared the printer to have this capability! */
	  /*if ( (duplex_mode) || (mode->flags & MODE_FLAG_NODUPLEX) ) {*/
	  i=0;
	  quality = mode->quality;
	  modefound=0;
	  while ( (muse->mode_name_list[i]!=NULL)  && (modefound != 1) ) {
	    for(j=0;j<caps->modelist->count;j++){
	      if(!strcmp(muse->mode_name_list[i],caps->modelist->modes[j].name)){/* find right place in canon-modes list */
		if ( (caps->modelist->modes[j].quality >= quality) ) {
		  if ( !(duplex_mode) || !(muse->use_flags & DUPLEX_SUPPORT) || !(caps->modelist->modes[j].flags & MODE_FLAG_NODUPLEX) ) {
		    /* duplex check */
		    if (caps->modelist->modes[j].ink_types & CANON_INK_K) { /* AND means support for CANON_IN_K is included */
		      mode = &caps->modelist->modes[j];
		      modefound=1;
		    }
		  }
		}
		break; /* go to next mode in muse list */
	      }
	    }
	    i++;
	  }
	  /*}*/
	}
	else { /* no restriction from PrintingMode if not set yet */
	  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both) PrintingMode not set yet\n");
	  /* if mode is not a matching duplex mode, need to find a new one */
	  /*if ( (duplex_mode) || (mode->flags & MODE_FLAG_NODUPLEX) ) {*/
	  i=0;
	  quality = mode->quality;
	  modefound=0;
	  while ( (muse->mode_name_list[i]!=NULL)  && (modefound != 1) ) {
	    for(j=0;j<caps->modelist->count;j++){
	      if(!strcmp(muse->mode_name_list[i],caps->modelist->modes[j].name)){/* find right place in canon-modes list */
		if ( (caps->modelist->modes[j].quality >= quality) ) {
		  if ( !(duplex_mode) || !(muse->use_flags & DUPLEX_SUPPORT) || !(caps->modelist->modes[j].flags & MODE_FLAG_NODUPLEX) ) {
		    /* duplex check */
		    mode = &caps->modelist->modes[j];
		    modefound=1;
		  }
		}
		break; /* go to next mode in muse list */
	      }
	    }
	    i++;
	  }
	  /*}*/
	}
	/* if no mode was found yet, repeat with no restrictions --- since some media may not allow PrintingMode to be what was selected */
	/*if ( (duplex_mode) || (mode->flags & MODE_FLAG_NODUPLEX) ) {*/
	if (modefound==0) {
	  i=0;
	  quality = mode->quality;
	  while ( (muse->mode_name_list[i]!=NULL)  && (modefound != 1) ) {
	    for(j=0;j<caps->modelist->count;j++){
	      if(!strcmp(muse->mode_name_list[i],caps->modelist->modes[j].name)){/* find right place in canon-modes list */
		if ( (caps->modelist->modes[j].quality >= quality) ) {
		  if ( !(duplex_mode) || !(muse->use_flags & DUPLEX_SUPPORT) || !(caps->modelist->modes[j].flags & MODE_FLAG_NODUPLEX) ) {
		    /* duplex check */
		    mode = &caps->modelist->modes[j];
		    modefound=1;
		    /* set PrintingMode to whatever the mode is capable of */
		    if (caps->modelist->modes[j].ink_types > CANON_INK_K) {
		      stp_set_string_parameter(v,"PrintingMode","Color");
		      printing_mode = stp_get_string_parameter(v, "PrintingMode");
		      stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both) PrintingMode set to Color\n");
		    } else {
		      stp_set_string_parameter(v,"PrintingMode","BW");
		      printing_mode = stp_get_string_parameter(v, "PrintingMode");
		      stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both) PrintingMode set to BW\n");
		    }
		  }
		}
		break; /* go to next mode in muse list */
	      }
	    }
	    i++;
	  }
	}

	ink_type=find_ink_type(v,mode,printing_mode);
#if 0
	/* if InkType does not match that of mode, change InkType to match it */
	/* choose highest color as default, as there is only one option for Black */
	/* if InkType does not match that of mode, change InkType to match it */
	/* choose highest color as default, as there is only one option for Black */
	if (printing_mode && !strcmp(printing_mode,"BW")) {
	  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType changed to %u (%s)\n",CANON_INK_K, "Gray");
	  stp_set_string_parameter(v, "InkType", "Gray");
	  ink_type = stp_get_string_parameter(v, "InkType");
	} else {
	  inkfound=0;
	  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType of mode %s is currently set as %s\n",mode->name,ink_type);
	  for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	    if (mode->ink_types & canon_inktypes[i].ink_type) { /* a mode can have several ink_types: must compare with ink_type if set */
	      if ( !(strcmp(ink_type,canon_inktypes[i].name))) {
		inkfound=1;
		stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType match found %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		ink_type = stp_get_string_parameter(v, "InkType");
		break;
	      }
	    }
	  }
	  /* if no match found choose first available inkset */
	  if (inkfound==0) {
	    for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	      if (mode->ink_types & canon_inktypes[i].ink_type) { /* a mode can have several ink_types: must compare with ink_type if set */
		if ((!ink_type) || (strcmp(ink_type,canon_inktypes[i].name))) { /* if InkType does not match selected mode ink type*/
		  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): No match found---InkType changed to %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		  stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		  ink_type = stp_get_string_parameter(v, "InkType");
		  inkfound=1; /* set */
		  break;
		}
	      }
	    }
	  }
	}
#endif

	/* end of cartridge option block */
	
	stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint: mode searching: replaced mode with: '%s'\n",mode->name);
	if (ERRPRINT)
	  stp_eprintf(v,"mode searching: replaced mode with: '%s'\n",mode->name);
	
#if 0
	/* set InkType for the mode decided upon */
	for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	  if (mode->ink_types & canon_inktypes[i].ink_type) {
	    if (strcmp(ink_type,canon_inktypes[i].name)) {
	      stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (Mode found): InkType changed to %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
	      stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
	      ink_type = stp_get_string_parameter(v, "InkType");
	      break;
	    }
	  }
	}
#endif
	
      }
    }/* added one here */
    else { /* we did find the mode in the list for media, so it should take precedence over other settings, as it is more specific. */

      stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (check_current_mode):  mode exists, need to check for consistency (%s)\n",mode->name);
      quality = mode->quality;
      /* Black InkSet */
      if (ink_set && !strcmp(ink_set,"Black")) {
	stp_set_string_parameter(v, "PrintingMode","BW");
	printing_mode = stp_get_string_parameter(v, "PrintingMode");
	if (!(mode->ink_types & CANON_INK_K)) {
	  /* need a new mode: 
	     loop through modes in muse list searching for a matching inktype, comparing quality
	  */
	  mode=suitable_mode_monochrome(v,muse,caps,quality,duplex_mode);
	  if (!mode)
	    modefound=0;
	  else
	    modefound=1;

	  if (modefound == 0) { /* still did not find a mode: pick first one for that media */
	    if ( (muse->use_flags & INKSET_BLACK_MODEREPL) ) {  
	      mode=find_first_matching_mode_monochrome(v,muse,caps,duplex_mode);
	    }
	    else {  /* no special replacement modes for black inkset */
	      mode=find_first_matching_mode(v,muse,caps,duplex_mode);
	    }
	  }
	  if (!mode)
	    modefound=0;
	  else
	    modefound=1;

	  ink_type=find_ink_type(v,mode,printing_mode);
#if 0	  
	  /* if InkType does not match that of mode, change InkType to match it */
	  /* choose highest color as default, as there is only one option for Black */
	  /* if InkType does not match that of mode, change InkType to match it */
	  /* choose highest color as default, as there is only one option for Black */
	  if (printing_mode && !strcmp(printing_mode,"BW")) {
	    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType changed to %u (%s)\n",CANON_INK_K, "Gray");
	    stp_set_string_parameter(v, "InkType", "Gray");
	    ink_type = stp_get_string_parameter(v, "InkType");
	  } else {
	    inkfound=0;
	    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType of mode %s is currently set as %s\n",mode->name,ink_type);
	    for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	      if (mode->ink_types & canon_inktypes[i].ink_type) { /* a mode can have several ink_types: must compare with ink_type if set */
		if ( !(strcmp(ink_type,canon_inktypes[i].name))) {
		  inkfound=1;
		  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType match found %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		  stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		  ink_type = stp_get_string_parameter(v, "InkType");
		  break;
		}
	      }
	    }
	    /* if no match found choose first available inkset */
	    if (inkfound==0) {
	      for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
		if (mode->ink_types & canon_inktypes[i].ink_type) { /* a mode can have several ink_types: must compare with ink_type if set */
		  if ((!ink_type) || (strcmp(ink_type,canon_inktypes[i].name))) { /* if InkType does not match selected mode ink type*/
		    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): No match found---InkType changed to %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		    stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		    ink_type = stp_get_string_parameter(v, "InkType");
		    inkfound=1; /* set */
		    break;
		  }
		}
	      }
	    }
	  }
#endif	  
#if 0
	  /* set InkType for the mode found */
	  for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	    if (mode->ink_types & canon_inktypes[i].ink_type) {
	      if (strcmp(ink_type,canon_inktypes[i].name)) { /* if InkType does not match selected mode ink type*/
		stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Black): InkType changed to %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		ink_type = stp_get_string_parameter(v, "InkType");
		break;
	      }
	    }
	  }
#endif

	}
	else {
	  /* mode is fine */
	  /* matched expected K inkset, but need to check if Duplex matches, and if not, get a new mode with right inkset */
	  mode=suitable_mode_monochrome(v,muse,caps,quality,duplex_mode);
	  if (!mode)
	    modefound=0;
	  else
	    modefound=1;

	  if (modefound == 0) { /* still did not find a mode: pick first one for that media */
	    if ( (muse->use_flags & INKSET_BLACK_MODEREPL) ) {  
	      mode=find_first_matching_mode_monochrome(v,muse,caps,duplex_mode);
	    }
	    else {  /* no special replacement modes for black inkset */
	      mode=find_first_matching_mode(v,muse,caps,duplex_mode);
	    }
	  }
	  if (!mode)
	    modefound=0;
	  else
	    modefound=1;

	  ink_type=find_ink_type(v,mode,printing_mode);
#if 0
	  /* if InkType does not match that of mode, change InkType to match it */
	  /* choose highest color as default, as there is only one option for Black */
	  /* if InkType does not match that of mode, change InkType to match it */
	  /* choose highest color as default, as there is only one option for Black */
	  if (printing_mode && !strcmp(printing_mode,"BW")) {
	    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType changed to %u (%s)\n",CANON_INK_K, "Gray");
	    stp_set_string_parameter(v, "InkType", "Gray");
	    ink_type = stp_get_string_parameter(v, "InkType");
	  } else {
	    inkfound=0;
	    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType of mode %s is currently set as %s\n",mode->name,ink_type);
	    for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	      if (mode->ink_types & canon_inktypes[i].ink_type) { /* a mode can have several ink_types: must compare with ink_type if set */
		if ( !(strcmp(ink_type,canon_inktypes[i].name))) {
		  inkfound=1;
		  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType match found %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		  stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		  ink_type = stp_get_string_parameter(v, "InkType");
		  break;
		}
	      }
	    }
	    /* if no match found choose first available inkset */
	    if (inkfound==0) {
	      for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
		if (mode->ink_types & canon_inktypes[i].ink_type) { /* a mode can have several ink_types: must compare with ink_type if set */
		  if ((!ink_type) || (strcmp(ink_type,canon_inktypes[i].name))) { /* if InkType does not match selected mode ink type*/
		    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): No match found---InkType changed to %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		    stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		    ink_type = stp_get_string_parameter(v, "InkType");
		    inkfound=1; /* set */
		    break;
		  }
		}
	      }
	    }
	  }
#endif	  
#if 0
	  /* set InkType for the mode found */
	  for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	    if (mode->ink_types & canon_inktypes[i].ink_type) {
	      if (strcmp(ink_type,canon_inktypes[i].name)) { /* if InkType does not match selected mode ink type*/
		stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Black): InkType changed to %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		ink_type = stp_get_string_parameter(v, "InkType");
		break;
	      }
	    }
	  }
#endif

	}
      } /* End of Black Inkset */
      /*-------------------------------------------------------------------------------------------------*/
      /* InkSet Color */
      else if ( (ink_set && !strcmp(ink_set,"Color")) && (caps->features & CANON_CAP_T) ) {
	stp_set_string_parameter(v, "PrintingMode","Color");
	printing_mode = stp_get_string_parameter(v, "PrintingMode");
	if (!(mode->ink_types & CANON_INK_CMY)) { /* Color InkSet */
	  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Color): inkset incorrect for Color cartridge---need new mode\n");
	  /* need a new mode
	     loop through modes in muse list searching for a matching inktype, comparing quality
	  */
	  mode=suitable_mode_color(v,muse,caps,quality,duplex_mode);

	  if (!mode)
	    modefound=0;
	  else
	    modefound=1;

	  if (modefound == 0) { /* still did not find a mode: pick first one for that media */
	    if ( (muse->use_flags & INKSET_COLOR_MODEREPL) ) {  
	      mode=find_first_matching_mode_monochrome(v,muse,caps,duplex_mode);
	      stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Color): Decided on first matching mode for color inkset (%s)\n",mode->name);
	    }
	    else {  /* no special replacement modes for color inkset */
	      mode=find_first_matching_mode(v,muse,caps,duplex_mode);
	      stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Color): Decided on first matching mode with no special replacement modes for color inkset (%s)\n",mode->name);
	    }
	  }
	  if (!mode)
	    modefound=0;
	  else
	    modefound=1;

	  ink_type=find_ink_type(v,mode,printing_mode);
#if 0
	  /* if InkType does not match that of mode, change InkType to match it */
	  /* choose highest color as default, as there is only one option for Black */
	  /* if InkType does not match that of mode, change InkType to match it */
	  /* choose highest color as default, as there is only one option for Black */
	  if (printing_mode && !strcmp(printing_mode,"BW")) {
	    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType changed to %u (%s)\n",CANON_INK_K, "Gray");
	    stp_set_string_parameter(v, "InkType", "Gray");
	    ink_type = stp_get_string_parameter(v, "InkType");
	  } else {
	    inkfound=0;
	    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType of mode %s is currently set as %s\n",mode->name,ink_type);
	    for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	      if (mode->ink_types & canon_inktypes[i].ink_type) { /* a mode can have several ink_types: must compare with ink_type if set */
		if ( !(strcmp(ink_type,canon_inktypes[i].name))) {
		  inkfound=1;
		  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType match found %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		  stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		  ink_type = stp_get_string_parameter(v, "InkType");
		  break;
		}
	      }
	    }
	    /* if no match found choose first available inkset */
	    if (inkfound==0) {
	      for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
		if (mode->ink_types & canon_inktypes[i].ink_type) { /* a mode can have several ink_types: must compare with ink_type if set */
		  if ((!ink_type) || (strcmp(ink_type,canon_inktypes[i].name))) { /* if InkType does not match selected mode ink type*/
		    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): No match found---InkType changed to %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		    stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		    ink_type = stp_get_string_parameter(v, "InkType");
		    inkfound=1; /* set */
		    break;
		  }
		}
	      }
	    }
	  }
#endif
#if 0
	  /* set InkType for the mode found */
	  for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	    if (mode->ink_types & canon_inktypes[i].ink_type) {
	      if (strcmp(ink_type,canon_inktypes[i].name)) { /* if InkType does not match selected mode ink type*/
		stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Color): InkType changed to %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		ink_type = stp_get_string_parameter(v, "InkType");
		break;
	      }
	    }
	  }
#endif

	}
	else {
	  /* mode is fine */
	  /* matched expected RGB inkset, but need to check if Duplex matches, and if not, get a new mode with right inkset */
	  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Color): inkset OK but need to check other parameters\n");
	  mode=suitable_mode_color(v,muse,caps,quality,duplex_mode); /* something wrong here!!! */
	  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Color): returned mode for color inkset: %s\n",mode->name);
	  if (!mode)
	    modefound=0;
	  else
	    modefound=1;

	  if (modefound == 0) { /* still did not find a mode: pick first one for that media */
	    if ( (muse->use_flags & INKSET_COLOR_MODEREPL) ) {
	      mode=find_first_matching_mode_monochrome(v,muse,caps,duplex_mode);
	      stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Color): Decided on first matching mode for color inkset (%s)\n",mode->name);
	    }
	    else {  /* no special replacement modes for color inkset */
	      mode=find_first_matching_mode(v,muse,caps,duplex_mode);
	      stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Color): Decided on first matching mode with no special replacement modes for color inkset (%s)\n",mode->name);
	    }
	  }
	  if (!mode)
	    modefound=0;
	  else
	    modefound=1;

	  ink_type=find_ink_type(v,mode,printing_mode);
#if 0
	  /* if InkType does not match that of mode, change InkType to match it */
	  /* choose highest color as default, as there is only one option for Black */
	  /* if InkType does not match that of mode, change InkType to match it */
	  /* choose highest color as default, as there is only one option for Black */
	  if (printing_mode && !strcmp(printing_mode,"BW")) {
	    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType changed to %u (%s)\n",CANON_INK_K, "Gray");
	    stp_set_string_parameter(v, "InkType", "Gray");
	    ink_type = stp_get_string_parameter(v, "InkType");
	  } else {
	    inkfound=0;
	    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType of mode %s is currently set as %s\n",mode->name,ink_type);
	    for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	      if (mode->ink_types & canon_inktypes[i].ink_type) { /* a mode can have several ink_types: must compare with ink_type if set */
		if ( !(strcmp(ink_type,canon_inktypes[i].name))) {
		  inkfound=1;
		  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType match found %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		  stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		  ink_type = stp_get_string_parameter(v, "InkType");
		  break;
		}
	      }
	    }
	    /* if no match found choose first available inkset */
	    if (inkfound==0) {
	      for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
		if (mode->ink_types & canon_inktypes[i].ink_type) { /* a mode can have several ink_types: must compare with ink_type if set */
		  if ((!ink_type) || (strcmp(ink_type,canon_inktypes[i].name))) { /* if InkType does not match selected mode ink type*/
		    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): No match found---InkType changed to %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		    stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		    ink_type = stp_get_string_parameter(v, "InkType");
		    inkfound=1; /* set */
		    break;
		  }
		}
	      }
	    }
	  }
#endif
#if 0
	  /* set InkType for the mode found */
	  for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	    if (mode->ink_types & canon_inktypes[i].ink_type) {
	      if (strcmp(ink_type,canon_inktypes[i].name)) { /* if InkType does not match selected mode ink type*/
		stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Color): InkType changed to %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		ink_type = stp_get_string_parameter(v, "InkType");
		break;
	      }
	    }
	  }
#endif

	}
      } /* End of Color Inkset */
      /*-------------------------------------------------------------------------------------------------*/
      /* Photo cartridge selection: only use modes that support it */
      else if (ink_set && !strcmp(ink_set,"Photo")) {
	/* Photo cartridge printing does not seem to have any monochrome option */
	stp_set_string_parameter(v, "PrintingMode","Color");
	printing_mode = stp_get_string_parameter(v, "PrintingMode");
	/* need to match photo cartridge mode flag */
	if (!(mode->flags & MODE_FLAG_PHOTO)) {
	  /* need a new mode
	     loop through modes in muse list searching for a matching inkset, comparing quality
	  */
	  mode=suitable_mode_photo(v,muse,caps,quality,duplex_mode);
	  if (!mode)
	    modefound=0;
	  else
	    modefound=1;

	  if (modefound == 0) { /* still did not find a mode: pick first one for that media */
	    if ( (muse->use_flags & INKSET_PHOTO_MODEREPL) ) {  
	      mode=find_first_matching_mode_photo(v,muse,caps,duplex_mode);
	    }
	    else {  /* no special replacement modes for photo inkset */
	      mode=find_first_matching_mode(v,muse,caps,duplex_mode);
	    }
	  }
	  if (!mode)
	    modefound=0;
	  else
	    modefound=1;

	  ink_type=find_ink_type(v,mode,printing_mode);
#if 0
	  /* if InkType does not match that of mode, change InkType to match it */
	  /* choose highest color as default, as there is only one option for Black */
	  /* if InkType does not match that of mode, change InkType to match it */
	  /* choose highest color as default, as there is only one option for Black */
	  if (printing_mode && !strcmp(printing_mode,"BW")) {
	    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType changed to %u (%s)\n",CANON_INK_K, "Gray");
	    stp_set_string_parameter(v, "InkType", "Gray");
	    ink_type = stp_get_string_parameter(v, "InkType");
	  } else {
	    inkfound=0;
	    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType of mode %s is currently set as %s\n",mode->name,ink_type);
	    for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	      if (mode->ink_types & canon_inktypes[i].ink_type) { /* a mode can have several ink_types: must compare with ink_type if set */
		if ( !(strcmp(ink_type,canon_inktypes[i].name))) {
		  inkfound=1;
		  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType match found %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		  stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		  ink_type = stp_get_string_parameter(v, "InkType");
		  break;
		}
	      }
	    }
	    /* if no match found choose first available inkset */
	    if (inkfound==0) {
	      for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
		if (mode->ink_types & canon_inktypes[i].ink_type) { /* a mode can have several ink_types: must compare with ink_type if set */
		  if ((!ink_type) || (strcmp(ink_type,canon_inktypes[i].name))) { /* if InkType does not match selected mode ink type*/
		    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): No match found---InkType changed to %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		    stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		    ink_type = stp_get_string_parameter(v, "InkType");
		    inkfound=1; /* set */
		    break;
		  }
		}
	      }
	    }
	  }
#endif	  
#if 0
	  /* set InkType for the mode found */
	  for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	    if (mode->ink_types & canon_inktypes[i].ink_type) {
	      if (strcmp(ink_type,canon_inktypes[i].name)) { /* if InkType does not match selected mode ink type*/
		stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Color): InkType changed to %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		ink_type = stp_get_string_parameter(v, "InkType");
		break;
	      }
	    }
	  }
#endif

	}
	else {
	  /* mode is fine */
	  /* matched expected inkset, but need to check if Duplex matches, and if not, get a new mode with right inkset */
	  mode=suitable_mode_photo(v,muse,caps,quality,duplex_mode);
	  if (!mode)
	    modefound=0;
	  else
	    modefound=1;

	  if (modefound == 0) { /* still did not find a mode: pick first one for that media */
	    if ( (muse->use_flags & INKSET_PHOTO_MODEREPL) ) {
	      mode=find_first_matching_mode_photo(v,muse,caps,duplex_mode);
	    }
	    else {  /* no special replacement modes for photo inkset */
	      mode=find_first_matching_mode(v,muse,caps,duplex_mode);
	    }
	  }
	  if (!mode)
	    modefound=0;
	  else
	    modefound=1;

	  ink_type=find_ink_type(v,mode,printing_mode);
#if 0
	  /* if InkType does not match that of mode, change InkType to match it */
	  /* choose highest color as default, as there is only one option for Black */
	  /* if InkType does not match that of mode, change InkType to match it */
	  /* choose highest color as default, as there is only one option for Black */
	  if (printing_mode && !strcmp(printing_mode,"BW")) {
	    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType changed to %u (%s)\n",CANON_INK_K, "Gray");
	    stp_set_string_parameter(v, "InkType", "Gray");
	    ink_type = stp_get_string_parameter(v, "InkType");
	  } else {
	    inkfound=0;
	    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType of mode %s is currently set as %s\n",mode->name,ink_type);
	    for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	      if (mode->ink_types & canon_inktypes[i].ink_type) { /* a mode can have several ink_types: must compare with ink_type if set */
		if ( !(strcmp(ink_type,canon_inktypes[i].name))) {
		  inkfound=1;
		  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType match found %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		  stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		  ink_type = stp_get_string_parameter(v, "InkType");
		  break;
		}
	      }
	    }
	    /* if no match found choose first available inkset */
	    if (inkfound==0) {
	      for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
		if (mode->ink_types & canon_inktypes[i].ink_type) { /* a mode can have several ink_types: must compare with ink_type if set */
		  if ((!ink_type) || (strcmp(ink_type,canon_inktypes[i].name))) { /* if InkType does not match selected mode ink type*/
		    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): No match found---InkType changed to %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		    stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		    ink_type = stp_get_string_parameter(v, "InkType");
		    inkfound=1; /* set */
		    break;
		  }
		}
	      }
	    }
	  }
#endif	  
#if 0
	  /* set InkType for the mode found */
	  for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	    if (mode->ink_types & canon_inktypes[i].ink_type) {
	      if (strcmp(ink_type,canon_inktypes[i].name)) { /* if InkType does not match selected mode ink type*/
		stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Color): InkType changed to %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		ink_type = stp_get_string_parameter(v, "InkType");
		break;
	      }
	    }
	  }
#endif

	} 
      } /* end of Photo Inkset  */
      /*-------------------------------------------------------------------------------------------------*/
      /* no restrictions for InkSet "Both" (non-BJC) or "Color" (BJC) or if no InkSet set yet */
      else {
	if (printing_mode && !strcmp(printing_mode,"Color")) {
	  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both) PrintingMode Color\n");
	  /* must skip K-only inksets if they exist: they only exist if the option "BW" is also declared but we cannot check if an option exists or not */
	  /*if ( (duplex_mode) || (mode->flags & MODE_FLAG_NODUPLEX) ) {*/
	    i=0;
	    quality = mode->quality;
	    modefound=0;
	    while ( (muse->mode_name_list[i]!=NULL)  && (modefound != 1) ) {
	      for(j=0;j<caps->modelist->count;j++){
		if(!strcmp(muse->mode_name_list[i],caps->modelist->modes[j].name)){/* find right place in canon-modes list */
		  if ( (caps->modelist->modes[j].quality >= quality) ) {
		    if ( !(duplex_mode) || !(muse->use_flags & DUPLEX_SUPPORT) || !(caps->modelist->modes[j].flags & MODE_FLAG_NODUPLEX) ) {
		      /* duplex check */
		      if (caps->modelist->modes[j].ink_types > CANON_INK_K) {
			if (!strcmp(mode->name,caps->modelist->modes[j].name)) {
			  mode = &caps->modelist->modes[j];
			  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both) Color: Decided on mode (%s)\n",mode->name);
			  modefound=1;
			}
		      }
		    }
		  }
		  break; /* go to next mode in muse list */
		}
	      }
	      i++;
	    }
	    /*}*/
	}
	else if (printing_mode && !strcmp(printing_mode,"BW")) {
	  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both) PrintingMode BW\n");
	  /* need to find K-only inksets: they must exist since we declared the printer to have this capability! */
	  /*if ( (duplex_mode) || (mode->flags & MODE_FLAG_NODUPLEX) ) {*/
	    i=0;
	    quality = mode->quality;
	    modefound=0;
	    while ( (muse->mode_name_list[i]!=NULL)  && (modefound != 1) ) {
	      for(j=0;j<caps->modelist->count;j++){
		if(!strcmp(muse->mode_name_list[i],caps->modelist->modes[j].name)){/* find right place in canon-modes list */
		  if ( (caps->modelist->modes[j].quality >= quality) ) {
		    if ( !(duplex_mode) || !(muse->use_flags & DUPLEX_SUPPORT) || !(caps->modelist->modes[j].flags & MODE_FLAG_NODUPLEX) ) {
		      /* duplex check */
		      if (caps->modelist->modes[j].ink_types & CANON_INK_K) { /* AND means CANON_INK_K is included in the support */
			if (!strcmp(mode->name,caps->modelist->modes[j].name)) {
			  mode = &caps->modelist->modes[j];
			  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both) BW: Decided on mode (%s)\n",mode->name);
			  modefound=1;
			}
		      }
		    }
		  }
		  break; /* go to next mode in muse list */
		}
	      }
	      i++;
	    }
	    /*}*/
	}
	else { /* no restriction from PrintingMode if not set yet */
	  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both) PrintingMode not set yet\n");
	  /* if mode is not a matching duplex mode, need to find a new one */
	  /*if ( (duplex_mode) || (mode->flags & MODE_FLAG_NODUPLEX) ) {*/
	    i=0;
	    quality = mode->quality;
	    modefound=0;
	    while ( (muse->mode_name_list[i]!=NULL)  && (modefound != 1) ) {
	      for(j=0;j<caps->modelist->count;j++){
		if(!strcmp(muse->mode_name_list[i],caps->modelist->modes[j].name)){/* find right place in canon-modes list */
		  if ( (caps->modelist->modes[j].quality >= quality) ) {
		    if ( !(duplex_mode) || !(muse->use_flags & DUPLEX_SUPPORT) || !(caps->modelist->modes[j].flags & MODE_FLAG_NODUPLEX) ) {
		      /* duplex check */
		      if (!strcmp(mode->name,caps->modelist->modes[j].name)) {
			mode = &caps->modelist->modes[j];
			stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both) PrintingMode not set yet: Decided on first matching mode with quality match (%s)\n",mode->name);
			modefound=1;
		      }
		    }
		  }
		  break; /* go to next mode in muse list */
		}
	      }
	      i++;
	    }
	    /*}*/
	}
	/* if no mode was found yet, repeat with no restrictions --- since some media may not allow PrintingMode to be what was selected */
	/*if ( (duplex_mode) || (mode->flags & MODE_FLAG_NODUPLEX) ) {*/
	if (modefound==0) {
	  i=0;
	  quality = mode->quality;
	  while ( (muse->mode_name_list[i]!=NULL)  && (modefound != 1) ) {
	    for(j=0;j<caps->modelist->count;j++){
	      if(!strcmp(muse->mode_name_list[i],caps->modelist->modes[j].name)){/* find right place in canon-modes list */
		if ( (caps->modelist->modes[j].quality >= quality) ) {
		  if ( !(duplex_mode) || !(muse->use_flags & DUPLEX_SUPPORT) || !(caps->modelist->modes[j].flags & MODE_FLAG_NODUPLEX) ) {
		    /* duplex check */
		    mode = &caps->modelist->modes[j];
		    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both) No mode previously found---catch-all: Decided on first matching mode (%s)\n",mode->name);
		    modefound=1;
		    /* set PrintingMode to whatever the mode is capable of */
		    if (caps->modelist->modes[j].ink_types > CANON_INK_K){
		      stp_set_string_parameter(v,"PrintingMode","Color");
		      printing_mode = stp_get_string_parameter(v, "PrintingMode");
		      stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both) PrintingMode set to Color\n");
		    } else {
		      stp_set_string_parameter(v,"PrintingMode","BW");
		      printing_mode = stp_get_string_parameter(v, "PrintingMode");
		      stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both) PrintingMode set to BW\n");
		    }
		  }
		}
		break; /* go to next mode in muse list */
	      }
	    }
	    i++;
	  }
	}

	ink_type=find_ink_type(v,mode,printing_mode);
#if 0
	/* if InkType does not match that of mode, change InkType to match it */
	/* choose highest color as default, as there is only one option for Black */
	/* if InkType does not match that of mode, change InkType to match it */
	/* choose highest color as default, as there is only one option for Black */
	if (printing_mode && !strcmp(printing_mode,"BW")) {
	  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType changed to %u (%s)\n",CANON_INK_K, "Gray");
	  stp_set_string_parameter(v, "InkType", "Gray");
	  ink_type = stp_get_string_parameter(v, "InkType");
	} else {
	  inkfound=0;
	  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType of mode %s is currently set as %s\n",mode->name,ink_type);
	  for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	    if (mode->ink_types & canon_inktypes[i].ink_type) { /* a mode can have several ink_types: must compare with ink_type if set */
	      if ( !(strcmp(ink_type,canon_inktypes[i].name))) {
		inkfound=1;
		stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): InkType match found %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		ink_type = stp_get_string_parameter(v, "InkType");
		break;
	      }
	    }
	  }
	  /* if no match found choose first available inkset */
	  if (inkfound==0) {
	    for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	      if (mode->ink_types & canon_inktypes[i].ink_type) { /* a mode can have several ink_types: must compare with ink_type if set */
		if ((!ink_type) || (strcmp(ink_type,canon_inktypes[i].name))) { /* if InkType does not match selected mode ink type*/
		  stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint (InkSet:Both): No match found---InkType changed to %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
		  stp_set_string_parameter(v, "InkType", canon_inktypes[i].name);
		  ink_type = stp_get_string_parameter(v, "InkType");
		  inkfound=1; /* set */
		  break;
		}
	      }
	    }
	  }
	}
#endif
      }
    }
  }
  /* end of mode replacement code */


#if 0
  if(quality && strcmp(quality, "None") == 0)
    quality = "Standard";

  if(quality && !strcmp(quality,"Standard")){
    return &caps->modelist->modes[caps->modelist->default_mode];
  }
#endif

#if 0
  /* only some modes can print to cd */
  if(input_slot && !strcmp(input_slot,"CD") && !(mode->flags & MODE_FLAG_CD)){
    for(i=0;i<caps->modelist->count;i++){
      if(caps->modelist->modes[i].flags & MODE_FLAG_CD){
	mode = &caps->modelist->modes[i];
	break;
      }
    }
  }
#endif


  if (mode) {
    stp_set_string_parameter(v, "Resolution",mode->text);  /* check_current_mode checks resolution! */
    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint:  check_current_mode --- updated Resolution: '%s'\n",mode->name);
  }

  if (mode) {
    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint:  check_current_mode --- Final returned mode: '%s'\n",mode->name);
    if (ERRPRINT)
      stp_eprintf(v,"check_current_mode --- Final returned mode: '%s'\n",mode->name);
  }
  else {
    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint:  check_current_mode --- Final returned mode is NULL \n");
    if (ERRPRINT)
      stp_eprintf(v,"check_current_mode --- Final returned mode is NULL \n");
  }

  /* set PrintingMode in case of Inkset precedence */
  if (mode) { /* final mode takes precedence */
    if (mode->ink_types == CANON_INK_K)
      stp_set_string_parameter(v, "PrintingMode", "BW");
    else
      stp_set_string_parameter(v, "PrintingMode", "Color");
  }
  else if (ink_type) { /* mode not yet known, but InkType known. InkSet should have been handled together with InkType above */
    if (!strcmp(ink_type,"Gray"))
      stp_set_string_parameter(v, "PrintingMode", "BW");
    else
      stp_set_string_parameter(v, "PrintingMode", "Color");
  }

  if (printing_mode)
    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint: Final PrintingMode %s\n",printing_mode);
  else /* should not happen */
    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint: Final PrintingMode is NULL\n");

  if (ink_set)
    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint: Final InkSet value (high priority): '%s'\n",ink_set);
  else
    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint: Final InkSet value is NULL\n");
  
  if (ink_type)
    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint: Final InkType value (low priority): '%s'\n",ink_type);
  else
    stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint: Final InkType value is NULL\n");

  return mode;
}

/* function returns the best ink_type for the current mode */
static unsigned int
canon_printhead_colors(const stp_vars_t*v)
{
  int i,j;
  const canon_mode_t* mode;
  const canon_cap_t * caps = canon_get_model_capabilities(v);
  const char *print_mode = stp_get_string_parameter(v, "PrintingMode");
  const char *ink_type = stp_get_string_parameter(v, "InkType");
  const char *ink_set = stp_get_string_parameter(v, "InkSet");

  stp_dprintf(STP_DBG_CANON, v,"Entered canon_printhead_colors: got PrintingMode %s\n",print_mode);
  if (ERRPRINT)
    stp_eprintf(v,"entered canon_printhead_colors: got PrintingMode %s\n",print_mode);

  /* if a mode is available, use it. Else mode is NULL */
  if (ERRPRINT)
    stp_eprintf(v,"Calling get_current_parameter from canon_printhead_colors");
  mode = canon_get_current_mode(v);
  
  /* get the printing mode again */
  print_mode = stp_get_string_parameter(v, "PrintingMode");

  /* if the printing mode was already selected as BW, accept it */
  if(print_mode && !strcmp(print_mode, "BW") && !(caps->features & CANON_CAP_NOBLACK) ){ /* workaround in case BW is a default */
    stp_dprintf(STP_DBG_CANON, v,"(canon_printhead_colors[BW]) Found InkType %u (CANON_INK_K)\n",CANON_INK_K);
    stp_dprintf(STP_DBG_CANON, v,"(canon_printhead_colors[BW]) NOBLACK? %lu\n",(caps->features & CANON_CAP_NOBLACK));
    if (ERRPRINT) {
      stp_eprintf(v,"(canon_printhead_colors[BW]) Found InkType %u (CANON_INK_K)\n",CANON_INK_K);
      stp_eprintf(v,"(canon_printhead_colors[BW]) NOBLACK? %lu\n",(caps->features & CANON_CAP_NOBLACK));
    }
    return CANON_INK_K;
  }
  /* alternatively, if the cartridge selection is in force, and black cartride is selected, accept it */
  if(ink_set && !strcmp(ink_set, "Black")){
    stp_dprintf(STP_DBG_CANON, v,"(canon_printhead_colors[BW]) Found InkSet black selection\n");
    if (ERRPRINT)
      stp_eprintf(v,"(canon_printhead_colors[BW]) Found InkSet black selection\n");
    return CANON_INK_K;
  }
  
  /* originaly finds selected InkType of form: CANON_INK_<inks> */
  /* but this is incorrect, since it does not check media or mode */
  /* change: deal with mode set and mode not set cases */

  /* if mode was already set, then return the ink types for only that mode */

  if (mode) {
    /* if an inktype selected check what it is */
    if(ink_type){
      for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	if (mode->ink_types & canon_inktypes[i].ink_type) {
	  stp_dprintf(STP_DBG_CANON, v,"(canon_printhead_colors[inktype]) Found InkType %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
	  if (ERRPRINT)
	    stp_eprintf(v,"(canon_printhead_colors[inktype]) Found InkType %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
	  return canon_inktypes[i].ink_type;
	}
      }
    }
    else {
      /* find the matching inks for the mode: chooses the first one found for a mode! */
      /* ink types are arranged in decreasing order so those with more meta inks are discovered first */
      for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	if(mode->ink_types & canon_inktypes[i].ink_type) {
	  stp_dprintf(STP_DBG_CANON, v,"(canon_printhead_colors[mode]) Found InkType %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
	  if (ERRPRINT)
	    stp_eprintf(v,"(canon_printhead_colors[mode]) Found InkType %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
	  return canon_inktypes[i].ink_type;
	}
      }
    }
  }
  else { /* mode not yet set */
    /* if an inktype selected check what it is */
    if(ink_type){
      for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	if(ink_type && !strcmp(canon_inktypes[i].name,ink_type)) {
	  stp_dprintf(STP_DBG_CANON, v,"(canon_printhead_colors[inktype]) Found InkType %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
	  if (ERRPRINT)
	    stp_eprintf(v,"(canon_printhead_colors[inktype]) Found InkType %i(%s)\n",canon_inktypes[i].ink_type,canon_inktypes[i].name);
	  return canon_inktypes[i].ink_type;
	}
      }
    }
    else { /* no ink type selected yet */
      if (ERRPRINT)
	stp_eprintf(v,"canon_printhead_colors: no mode and no inktype: we have to choose the highest one to return\n");
      /* loop through all modes, and return the highest inktype found */
      for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	for(j=0;j<caps->modelist->count;j++){
	  if(caps->modelist->modes[j].ink_types & canon_inktypes[i].ink_type){
	    stp_dprintf(STP_DBG_CANON, v," highest inktype found ---  %s(%s)\n",canon_inktypes[i].name,canon_inktypes[i].text);
	    if (ERRPRINT)
	      stp_eprintf(v,"highest inktype found --- %s(%s)\n",canon_inktypes[i].name,canon_inktypes[i].text);
	    return canon_inktypes[i].ink_type;
	  }
	}
      }
    }
    
  }

  /* originally as fallback choose CANON_INK_K */
  /* However, some Canon printers do not have monochrome mode at all, only color meta ink modes, like iP6000 series */
#if 0
  stp_dprintf(STP_DBG_CANON, v,"(canon_printhead_colors[fall-through]) Returning InkType %i(CANON_INK_K)\n",CANON_INK_K);
  if (ERRPRINT)
    stp_eprintf(v,"(canon_printhead_colors[fall-through]) Found InkType %i(CANON_INK_K)\n",CANON_INK_K);
  return CANON_INK_K;
#endif
  /* new fallback: loop through ink type in reverse order, picking first one found, which if CANON_INK_K is supported will be that, else the lowest amount of color */
  for(i=((sizeof(canon_inktypes)/sizeof(canon_inktypes[0]))-1);i>=0;i--){
    for(j=0;j<caps->modelist->count;j++){
      if(caps->modelist->modes[j].ink_types & canon_inktypes[i].ink_type){
	stp_dprintf(STP_DBG_CANON, v," lowest inktype found ---  %s(%s)\n",canon_inktypes[i].name,canon_inktypes[i].text);
	if (ERRPRINT)
	  stp_eprintf(v,"lowest inktype found --- %s(%s)\n",canon_inktypes[i].name,canon_inktypes[i].text);
	return canon_inktypes[i].ink_type;
      }
    }
  }

  /* if fails until here, return something reasonable in most situations */
  return CANON_INK_K;
  
}

static unsigned char
canon_size_type(const stp_vars_t *v, const canon_cap_t * caps)
{
  const stp_papersize_t *pp = stp_get_papersize_by_size(stp_get_page_height(v),
							stp_get_page_width(v));
  if (pp)
    {
      const char *name = pp->name;
      /* used internally: do not translate */
      /* built ins:                                  Japanese driver notation */
      if (!strcmp(name,"A5"))          return 0x01;
      if (!strcmp(name,"A4"))          return 0x03;
      if (!strcmp(name,"A3"))          return 0x05;
      if (!strcmp(name,"B5"))          return 0x08; 
      if (!strcmp(name,"B4"))          return 0x0a;
      if (!strcmp(name,"Letter"))      return 0x0d;
      if (!strcmp(name,"Legal"))       return 0x0f;
      if (!strcmp(name,"Tabloid"))     return 0x11; /* 11x17 */
      if (!strcmp(name,"w283h420"))    return 0x14; /* Hagaki */
      /*      if (!strcmp(name,"COM10"))       return 0x16;*/
      /*      if (!strcmp(name,"DL"))          return 0x17;*/
      if (!strcmp(name,"LetterExtra")) return 0x2a; /* Letter navi --- Letter+ */
      if (!strcmp(name,"A4Extra"))     return 0x2b; /* A4navi --- A4+ */
      if (!strcmp(name,"A3plus"))      return 0x2c; /* A3navi --- A3+ */
      if (!strcmp(name,"w288h144"))    return 0x2d; /* ??? */
      if (!strcmp(name,"COM10"))       return 0x2e; /* US Comm #10 Env */
      if (!strcmp(name,"DL"))          return 0x2f; /* Euro DL Env */
      if (!strcmp(name,"w297h666"))    return 0x30; /* Western Env #4 (you4) */
      if (!strcmp(name,"w277h538"))    return 0x31; /* Western Env #6 (you6) */
      if (!strcmp(name,"w252h360J"))   return 0x32; /* L --- similar to US 3.5x5 size */
      if (!strcmp(name,"w360h504J"))   return 0x33; /* 2L --- similar to US5x7 */
      if (!strcmp(name,"w288h432J"))   return 0x34; /* KG --- same size as US 4x6 */
      if (!strcmp(name,"w155h257"))    return 0x36; /* Japanese Business Card 55mm x 91mm */
      if (!strcmp(name,"w360h504"))    return 0x37; /* US5x7 */
      if (!strcmp(name,"w420h567"))    return 0x39; /* Ofuku Hagaki */
      if (!strcmp(name,"w340h666"))    return 0x3a; /* Japanese Long Env #3 (chou3) */
      if (!strcmp(name,"w255h581"))    return 0x3b; /* Japanese Long Env #4 (chou4) */
      if (!strcmp(name,"w155h244"))    return 0x41; /* Business/Credit Card 54mm x 86mm */
      /* if (!strcmp(name,"A4"))       return 0x42; */ /* FineArt A4 35mm border --- iP7100: gap is 18 */
      /* if (!strcmp(name,"A3"))       return 0x43; */ /* FineArt A3 35mm border --- iP7100: gap is 18 */
      /* if (!strcmp(name,"Letter"))   return 0x44; */ /* FineArt Letter 35mm border --- iP7100: gap is 18 */
      if (!strcmp(name,"w288h576"))    return 0x46; /* US4x8 */
      if (!strcmp(name,"w1008h1224J")) return 0x47; /* HanKire --- 14in x 17in */
      if (!strcmp(name,"720h864J"))    return 0x48; /* YonKire --- 10in x 12 in*/
      if (!strcmp(name,"c8x10J"))      return 0x49; /* RokuKire --- same size as 8x10 */
      /* if (!strcmp(name,"A4"))       return 0x4d; */ /* ArtA4 35mm border */
      /* if (!strcmp(name,"A3"))       return 0x4e; */ /* ArtA3 35mm border */
      /* if (!strcmp(name,"Letter"))   return 0x4f; */ /* ArtLetter 35mm border */
      if (!strcmp(name,"w288h512"))    return 0x52; /* Wide101.6x180.6 */
      /* w283h566 Wide postcard 148mm x 200mm */

      /* media size codes for CD (and other media depending on printer model */
      if (!strcmp(name,"CD5Inch"))    return 0x53; /* CD --- arbitrary choice here, modify in ESC (P command */
      /* similar needed for FineArt media which have common sizes but different codes */

      /* custom */

      stp_deprintf(STP_DBG_CANON,"canon: Unknown paper size '%s' - using custom\n",name);
    } else {
      stp_deprintf(STP_DBG_CANON,"canon: Couldn't look up paper size %dx%d - "
	      "using custom\n",stp_get_page_height(v), stp_get_page_width(v));
    }
  return 0;
}

static void
canon_describe_resolution(const stp_vars_t *v, int *x, int *y)
{
  const canon_mode_t* mode = NULL;
  const canon_cap_t * caps = canon_get_model_capabilities(v);
 
  /* if mode is not yet set, it remains NULL */
  if (ERRPRINT)
    stp_eprintf(v,"Calling get_current_parameter from canon_describe_resolution");
  mode = canon_get_current_mode(v);

  if(!mode)
    mode = &caps->modelist->modes[caps->modelist->default_mode];

  if (mode) {
    *x = mode->xdpi;
    *y = mode->ydpi;
  }
}

static const char *
canon_describe_output(const stp_vars_t *v)
{
  unsigned int ink_type = canon_printhead_colors(v);

  if(ink_type & CANON_INK_CMYK_MASK)
    return "CMYK";
  if(ink_type & CANON_INK_CMY_MASK)
    return "CMY";
  /* Gernot added */
  /*if(ink_type & CANON_INK_cmy_MASK)
    return "cmy";*/
  return "Grayscale";
}

/*
 * 'canon_parameters()' - Return the parameter values for the given parameter.
 */

static stp_parameter_list_t
canon_list_parameters(const stp_vars_t *v)
{
  stp_parameter_list_t *ret = stp_parameter_list_create();
  int i;
  for (i = 0; i < the_parameter_count; i++)
    stp_parameter_list_add_param(ret, &(the_parameters[i]));
  for (i = 0; i < float_parameter_count; i++)
    stp_parameter_list_add_param(ret, &(float_parameters[i].param));
  return ret;
}

static void
canon_parameters(const stp_vars_t *v, const char *name,
		 stp_parameter_t *description)
{
  int		i,j;

  const canon_cap_t * caps=
    canon_get_model_capabilities(v);
  description->p_type = STP_PARAMETER_TYPE_INVALID;

  if (name == NULL)
    return;

  for (i = 0; i < float_parameter_count; i++)
    if (strcmp(name, float_parameters[i].param.name) == 0)
      {
	/* presumably need to return the maximum number of inks the printer can handle */
	unsigned int ink_type = canon_printhead_colors(v);

	stp_fill_parameter_settings(description,
				    &(float_parameters[i].param));
	description->deflt.dbl = float_parameters[i].defval;
	description->bounds.dbl.upper = float_parameters[i].max;
	description->bounds.dbl.lower = float_parameters[i].min;
	if (ink_type != CANON_INK_K || !float_parameters[i].color_only)
	  description->is_active = 1;
	else
	  description->is_active = 0;
	return;
      }

  for (i = 0; i < the_parameter_count; i++)
    if (strcmp(name, the_parameters[i].name) == 0)
      {
	stp_fill_parameter_settings(description, &(the_parameters[i]));
	break;
      }
  if (strcmp(name, "PageSize") == 0)
    {
      const char* input_slot = stp_get_string_parameter(v, "InputSlot");
      int height_limit, width_limit;
      int papersizes = stp_known_papersizes();
      description->bounds.str = stp_string_list_create();

      width_limit = caps->max_width;
      height_limit = caps->max_height;

      if(input_slot && !strcmp(input_slot,"CD")){
        stp_string_list_add_string
          (description->bounds.str, "CD5Inch", _("CD - 5 inch"));
        stp_string_list_add_string
          (description->bounds.str, "CD3Inch", _("CD - 3 inch"));
        stp_string_list_add_string
          (description->bounds.str, "CDCustom", _("CD - Custom"));
      }else{
        for (i = 0; i < papersizes; i++) {
          const stp_papersize_t *pt = stp_get_papersize_by_index(i);
          if (strlen(pt->name) > 0 &&
	      pt->width <= width_limit && pt->height <= height_limit){
	    stp_string_list_add_string(description->bounds.str,
				     pt->name, gettext(pt->text));
           }
        }
      }
      description->deflt.str =
        stp_string_list_param(description->bounds.str, 0)->name;
  }
  else if (strcmp(name, "CDInnerRadius") == 0 )
    {
      const char* input_slot = stp_get_string_parameter(v, "InputSlot");
      description->bounds.str = stp_string_list_create();
      if (input_slot && !strcmp(input_slot,"CD") &&
         (!stp_get_string_parameter(v, "PageSize") ||
          strcmp(stp_get_string_parameter(v, "PageSize"), "CDCustom") != 0))
	{
	  stp_string_list_add_string
	    (description->bounds.str, "None", _("Normal"));
	  stp_string_list_add_string
	    (description->bounds.str, "Small", _("Print To Hub"));
	  description->deflt.str =
	    stp_string_list_param(description->bounds.str, 0)->name;
	}
      else
	description->is_active = 0;
    }
  else if (strcmp(name, "CDInnerDiameter") == 0 )
    {
      const char* input_slot = stp_get_string_parameter(v, "InputSlot");
      description->bounds.dimension.lower = 16 * 10 * 72 / 254;
      description->bounds.dimension.upper = 43 * 10 * 72 / 254;
      description->deflt.dimension = 43 * 10 * 72 / 254;
      if (input_slot && !strcmp(input_slot,"CD") &&
         (!stp_get_string_parameter(v, "PageSize") ||
         strcmp(stp_get_string_parameter(v, "PageSize"), "CDCustom") == 0))
	description->is_active = 1;
      else
	description->is_active = 0;
    }
  else if (strcmp(name, "CDOuterDiameter") == 0 )
    {
      const char* input_slot = stp_get_string_parameter(v, "InputSlot");
      description->bounds.dimension.lower = 65 * 10 * 72 / 254;
      description->bounds.dimension.upper = 120 * 10 * 72 / 254;
      description->deflt.dimension = 329;
      if (input_slot && !strcmp(input_slot,"CD") &&
         (!stp_get_string_parameter(v, "PageSize") ||
          strcmp(stp_get_string_parameter(v, "PageSize"), "CDCustom") == 0))
	description->is_active = 1;
      else
	description->is_active = 0;
    }
  else if (strcmp(name, "CDXAdjustment") == 0 ||
	   strcmp(name, "CDYAdjustment") == 0)
    {
      const char* input_slot = stp_get_string_parameter(v, "InputSlot");
      description->bounds.dimension.lower = -15;
      description->bounds.dimension.upper = 15;
      description->deflt.dimension = 0;
      if (input_slot && !strcmp(input_slot,"CD"))
	description->is_active = 1;
      else
	description->is_active = 0;
    }
  else if (strcmp(name, "Resolution") == 0)
  {
#if 0
    const char* input_slot = stp_get_string_parameter(v, "InputSlot");
#endif
    description->bounds.str= stp_string_list_create();
    description->deflt.str = NULL;
    for(i=0;i<caps->modelist->count;i++){
#if 0
	if(!(input_slot && !strcmp(input_slot,"CD") && !(caps->modelist->modes[i].flags & MODE_FLAG_CD)))
#endif
          stp_string_list_add_string(description->bounds.str,
				     caps->modelist->modes[i].name, gettext(caps->modelist->modes[i].text));
        stp_deprintf(STP_DBG_CANON,"supports mode '%s'\n",
		     caps->modelist->modes[i].name);
        if(i == caps->modelist->default_mode)
	  description->deflt.str=caps->modelist->modes[i].name;
    }
  }
  else if (strcmp(name, "InkType") == 0)
  {
    const canon_mode_t* mode = NULL;

    if (ERRPRINT)
      stp_eprintf(v,"Calling get_current_parameter from InkType block in canon_parameters");
    mode=canon_get_current_mode(v);

    description->bounds.str= stp_string_list_create();
    if (mode) {
      for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	if(mode->ink_types & canon_inktypes[i].ink_type){
          stp_string_list_add_string(description->bounds.str,canon_inktypes[i].name,_(canon_inktypes[i].text));
	  stp_dprintf(STP_DBG_CANON, v," mode known --- Added InkType %s(%s) for mode %s (inktype %u)\n",canon_inktypes[i].name,canon_inktypes[i].text,mode->name,mode->ink_types);
	  if (ERRPRINT)
	    stp_eprintf(v,"mode known --- Added InkType %s(%s) for mode %s (inktype %u)\n",canon_inktypes[i].name,canon_inktypes[i].text,mode->name,mode->ink_types);
	}
      }
      description->deflt.str = stp_string_list_param(description->bounds.str, 0)->name;
    }
    /* mode not defined yet --- needed for PPD generation */
    else {
      for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	for(j=0;j<caps->modelist->count;j++){
	  if(caps->modelist->modes[j].ink_types & canon_inktypes[i].ink_type){
	    stp_string_list_add_string(description->bounds.str,canon_inktypes[i].name,_(canon_inktypes[i].text));
	    stp_dprintf(STP_DBG_CANON, v," no mode --- Added InkType %s(%s) for mode (%s) inktypes %u\n",canon_inktypes[i].name,canon_inktypes[i].text,caps->modelist->modes[j].name,caps->modelist->modes[j].ink_types);
	    if (ERRPRINT)
	      stp_eprintf(v,"no mode --- Added InkType %s(%s) for mode (%s) inktypes %u\n",canon_inktypes[i].name,canon_inktypes[i].text,caps->modelist->modes[j].name,caps->modelist->modes[j].ink_types);
	    break;
	  }      
	}
      }
      /* default type must be deduced from the default mode */
      /* use color if available, so break after first (color) is found, since inkt types ordered with gray last */
      for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	if(caps->modelist->modes[caps->modelist->default_mode].ink_types & canon_inktypes[i].ink_type){
	  description->deflt.str = canon_inktypes[i].name;
	  break;
	}      
      }
    }
    /* default type must be deduced from the default mode */
    /*description->deflt.str = stp_string_list_param(description->bounds.str, 0)->name;*/
  }
  else if (strcmp(name, "InkChannels") == 0)
    {
      unsigned int ink_type = canon_printhead_colors(v);
      for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	if(ink_type == canon_inktypes[i].ink_type){
              description->deflt.integer = canon_inktypes[i].num_channels;
	      stp_dprintf(STP_DBG_CANON, v,"Added %d InkChannels\n",canon_inktypes[i].num_channels);
	      if (ERRPRINT)
		stp_eprintf(v,"Added %d InkChannels\n",canon_inktypes[i].num_channels);
	}
      }
      description->bounds.integer.lower = -1;
      description->bounds.integer.upper = -1;
    }
  else if (strcmp(name, "MediaType") == 0)
  {
    const canon_paper_t * canon_paper_list = caps->paperlist->papers;
    int count = caps->paperlist->count;
    description->bounds.str= stp_string_list_create();
    description->deflt.str= canon_paper_list[0].name;

    for (i = 0; i < count; i ++) {
      stp_string_list_add_string(description->bounds.str,
				canon_paper_list[i].name,
				gettext(canon_paper_list[i].text));

      stp_dprintf(STP_DBG_CANON, v,"DEBUG: Gutenprint:  Added Media Type: '%s'\n",canon_paper_list[i].name);
    }
  }
  else if (strcmp(name, "InputSlot") == 0)
  {
    const canon_slot_t * canon_slot_list = caps->slotlist->slots;
    int count = caps->slotlist->count;
    description->bounds.str= stp_string_list_create();
    description->deflt.str= canon_slot_list[0].name;

    for (i = 0; i < count; i ++)
      stp_string_list_add_string(description->bounds.str,
				canon_slot_list[i].name,
				gettext(canon_slot_list[i].text));
  }
  else if (strcmp(name, "PrintingMode") == 0)
  {
    int found_color, found_mono;
    const canon_mode_t* mode = NULL;
    /* mode remains NULL if not yet set */
    
    if (ERRPRINT)
      stp_eprintf(v,"Calling get_current_mode from PrintingMode block in canon_parameter");
    mode = canon_get_current_mode(v);
    
    /* If mode is not set need to search ink types for all modes and
       see whether we have any color there
     */

    if (ERRPRINT)
      stp_eprintf(v,"PrintingMode---entered enumeration block in canon_printers\n");

    description->bounds.str = stp_string_list_create();

    if (ERRPRINT)
      stp_eprintf(v,"PrintingMode---created list\n");

    if (mode) {
      if (ERRPRINT)
	stp_eprintf(v,"PrintingMode: (mode known) what is the current mode inktype value: %i\n",mode->ink_types);
      /* e.g., ink_types is 21 = 16 + 4 + 1 */
      if (mode->ink_types > 1) {
	stp_string_list_add_string
	  (description->bounds.str, "Color", _("Color"));
	if (ERRPRINT)
	  stp_eprintf(v,"PrintingMode: (mode known) added Color\n");
      }
      if (mode->ink_types & CANON_INK_K) {
	stp_string_list_add_string
	  (description->bounds.str, "BW", _("Black and White"));
	if (ERRPRINT)
	  stp_eprintf(v,"PrintingMode: (mode known) added BW\n");
      }
    }
#if 0
      /* original code */
      if (mode)
	if (mode->ink_types != CANON_INK_K) {
	  stp_string_list_add_string
	    (description->bounds.str, "Color", _("Color"));
	  if (ERRPRINT)
	    stp_eprintf(v,"PrintingMode: (mode known) added Color\n");
	}
#endif

    else { /* mode not known yet --- needed for PPD generation */
      if (ERRPRINT)
	stp_eprintf(v,"PrintingMode: entered mode not known conditional block\n");
      /* add code to find color inks */
      /* default type must be deduced from the default mode */
      /* use color if available, so break after first (color) is found, since ink types ordered with gray last */
      found_color=0;
      for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	for(j=0;j<caps->modelist->count;j++){
	  if(caps->modelist->modes[j].ink_types > 1){
	    stp_string_list_add_string
	      (description->bounds.str, "Color", _("Color"));
	    found_color=1;
	    if (ERRPRINT)
	      stp_eprintf(v,"PrintingMode: (mode not known) added Color\n");
	    break;
	  }
	}
	if (found_color==1)
	  break;
      }
      found_mono=0;
      for(i=0;i<sizeof(canon_inktypes)/sizeof(canon_inktypes[0]);i++){
	for(j=0;j<caps->modelist->count;j++){
	  if(caps->modelist->modes[j].ink_types & CANON_INK_K){
	    stp_string_list_add_string
	      (description->bounds.str, "BW", _("Black and White"));
	    found_mono=1;
	    if (ERRPRINT)
	      stp_eprintf(v,"PrintingMode: (mode not known) added BW\n");
	    break;
	  }
	}
	if (found_mono==1)
	  break;
      }

#if 0
      /* ink types for default mode*/
      if(caps->modelist->modes[caps->modelist->default_mode].ink_types > 1){
	stp_string_list_add_string
	  (description->bounds.str, "Color", _("Color"));
	if (ERRPRINT)
	  stp_eprintf(v,"PrintingMode: (mode not known) added Color\n");
      }
      if(caps->modelist->modes[caps->modelist->default_mode].ink_types & CANON_INK_K){
	stp_string_list_add_string
	(description->bounds.str, "BW", _("Black and White"));
	if (ERRPRINT)
	  stp_eprintf(v,"PrintingMode: (mode not known) added BW\n");	
      }
#endif
#if 0
      /* original code */
      stp_string_list_add_string
	(description->bounds.str, "BW", _("Black and White"));
      if (ERRPRINT)
	stp_eprintf(v,"PrintingMode: added BW\n");
#endif
    }
    
    /* original code --- fine as is */
    description->deflt.str =
      stp_string_list_param(description->bounds.str, 0)->name;
  } 
  else if (strcmp(name, "InkSet") == 0)
    {
      description->bounds.str= stp_string_list_create();
      if (caps->features & CANON_CAP_T) {
	stp_string_list_add_string
	  (description->bounds.str, "Both", _("Both"));
	if (!(caps->features & CANON_CAP_NOBLACK)) {
	    stp_string_list_add_string
	      (description->bounds.str, "Black", _("Black"));
	}
	stp_string_list_add_string
	  (description->bounds.str, "Color", _("Color"));
      } /* mutually exclusive */
      else if (caps->features & CANON_CAP_cart) {
	stp_string_list_add_string
	  (description->bounds.str, "Color", _("Color"));
	stp_string_list_add_string
	  (description->bounds.str, "Black", _("Black"));
	stp_string_list_add_string
	  (description->bounds.str, "Photo", _("Photo"));
      } else {
	/* make sure to have at least a default value: no choice */
	stp_string_list_add_string
	  (description->bounds.str, "None", _("None"));
      }
      description->deflt.str =
	stp_string_list_param(description->bounds.str, 0)->name;
    }
  /* Test implementation of borderless printing */
  else if (strcmp(name, "FullBleed") == 0)
    {
      const char* input_slot = stp_get_string_parameter(v, "InputSlot");
      if (input_slot && !strcmp(input_slot,"CD"))
	description->is_active = 0;
      else if (caps->features & CANON_CAP_BORDERLESS)
	description->deflt.boolean = 0;
      else
	description->is_active = 0;
    }
  else if (strcmp(name, "Duplex") == 0)
  {
    int offer_duplex=0;

    description->bounds.str = stp_string_list_create();

/*
 * Don't offer the Duplex/Tumble options if the JobMode parameter is
 * set to "Page" Mode.
 * "Page" mode is set by the Gimp Plugin, which only outputs one page at a
 * time, so Duplex/Tumble is meaningless.
 */

    if (stp_get_string_parameter(v, "JobMode"))
        offer_duplex = strcmp(stp_get_string_parameter(v, "JobMode"), "Page");
    else
     offer_duplex=1;

    if (offer_duplex && (caps->features & CANON_CAP_DUPLEX))
    {
      description->deflt.str = duplex_types[0].name;
      for (i=0; i < NUM_DUPLEX; i++)
        {
          stp_string_list_add_string(description->bounds.str,
				     duplex_types[i].name,gettext(duplex_types[i].text));
        }
    }
    else
      description->is_active = 0;
  }
  else if (strcmp(name, "Quality") == 0)
  {
#if 0
    int has_standard_quality = 0;
#endif
    description->bounds.str = stp_string_list_create();
    stp_string_list_add_string(description->bounds.str, "None",
			       _("Manual Control"));
    stp_string_list_add_string(description->bounds.str, "Standard",
			       _("Standard"));
    description->deflt.str = "Standard";
  }
  /* Cartridge selection for those printers that have it */
  else if (strcmp(name, "Cartridge") == 0)
  {
#if 0
    int offer_cartridge_selection = 0;
#endif
    description->bounds.str = stp_string_list_create();
    stp_string_list_add_string(description->bounds.str, "Both",
			       _("Both"));
    stp_string_list_add_string(description->bounds.str, "Color",
			       _("Color"));
    stp_string_list_add_string(description->bounds.str, "Black",
			       _("Black"));

    /* description->deflt.str = "Both"; */
    /* Note: not necessary set cartridge if Mono mode */

    if (caps->features & CANON_CAP_CARTRIDGE)
      {
	description->deflt.str =
	  stp_string_list_param(description->bounds.str, 0)->name;
      }
    else
      description->is_active = 0;
  }

}


/*
 * 'canon_imageable_area()' - Return the imageable area of the page.
 */

static void
internal_imageable_area(const stp_vars_t *v,   /* I */
			int  use_paper_margins,
			int use_maximum_area,
			int  *left,	/* O - Left position in points */
			int  *right,	/* O - Right position in points */
			int  *bottom,	/* O - Bottom position in points */
			int  *top)	/* O - Top position in points */
{
  int width, length;			/* Size of page */
  int cd = 0;                           /* CD selected */
  const char *media_size = stp_get_string_parameter(v, "PageSize");
  int left_margin = 0;
  int right_margin = 0;
  int bottom_margin = 0;
  int top_margin = 0;
  const stp_papersize_t *pt = NULL;
  const char* input_slot = stp_get_string_parameter(v, "InputSlot");

  const canon_cap_t * caps= canon_get_model_capabilities(v);

  if (media_size)
    pt = stp_get_papersize_by_name(media_size);

  if(input_slot && !strcmp(input_slot,"CD"))
    cd = 1;

  stp_default_media_size(v, &width, &length);
  if (cd) {
    /* ignore printer margins for the cd print, margins get adjusted in do_print for now */
    if (pt) {
      /* move code from do_print here */
    }
    else {
      /* move code from do_print here */
    }
  }
  /* non-CD media */
  else {
    if (pt && use_paper_margins) {
      left_margin = pt->left;
      right_margin = pt->right;
      bottom_margin = pt->bottom;
      top_margin = pt->top;
    }
    /* limit to printer capabilities---without fullbleed */
    left_margin = MAX(left_margin, caps->border_left);
    right_margin = MAX(right_margin, caps->border_right);
    top_margin = MAX(top_margin, caps->border_top);
    bottom_margin = MAX(bottom_margin, caps->border_bottom);
  }

  /* temporarily limit to non-CD media until page size code moved here from do_print */
  /* Note: written beloe code to handle CD case as well */
  if(!cd){
    if (ERRPRINT) {
      stp_eprintf(v,"internal_imageable_area: about to enter the borderless condition block\n");
      stp_eprintf(v,"internal_imageable_area: is borderless available? %016lx\n",caps->features & CANON_CAP_BORDERLESS);
      stp_eprintf(v,"internal_imageable_area: is borderless selected? %d\n",stp_get_boolean_parameter(v, "FullBleed"));
    }
    
    if ( (caps->features & CANON_CAP_BORDERLESS) &&
	 (use_maximum_area || (!cd && stp_get_boolean_parameter(v, "FullBleed")))) {
      
      if (ERRPRINT)
	stp_eprintf(v,"internal_imageable_area: entered borderless condition\n");
      
      if (pt) {
	
	if (ERRPRINT)
	  stp_eprintf(v,"internal_imageable_area: entered pt condition\n");
	
	if (pt->left <= 0 && pt->right <= 0 && pt->top <= 0 && pt->bottom <= 0) {
	  
	  if (ERRPRINT)
	    stp_eprintf(v,"internal_imageable_area: enetered margin<=0 condition\n");
	  
	  if (use_paper_margins) {
	    unsigned width_limit = caps->max_width;
	    left_margin = -8;
	    right_margin = -8;
	    if (width - right_margin - 3 > width_limit)
	      right_margin = width - width_limit - 3;
	    top_margin = -6;
	    bottom_margin = -15;
	    
	    if (ERRPRINT)
	      stp_eprintf(v,"internal_imageable_area: use_paper_margins so set margins all to -7\n");

	  }
	  else {
	    left_margin = 0;
	    right_margin = 0;
	    top_margin = 0;
	    bottom_margin = 0;
	    
	    if (ERRPRINT)
	      stp_eprintf(v,"internal_imageable_area: does not use paper margins so set margins all to 0\n");

	  }
	}
      }
    }
  }

  if (ERRPRINT) 
    {
      stp_eprintf(v,"internal_imageable_area: left_margin %d\n",left_margin);
      stp_eprintf(v,"internal_imageable_area: right_margin %d\n",right_margin);
      stp_eprintf(v,"internal_imageable_area: top_margin %d\n",top_margin);
      stp_eprintf(v,"internal_imageable_area: bottom_margin %d\n",bottom_margin);
    }

  *left =	left_margin;
  *right =	width - right_margin;
  *top =	top_margin;
  *bottom =	length - bottom_margin;

  if (ERRPRINT) 
    {
      stp_eprintf(v,"internal_imageable_area: page_left %d\n",*left);
      stp_eprintf(v,"internal_imageable_area: page_right %d\n",*right);
      stp_eprintf(v,"internal_imageable_area: page_top %d\n",*top);
      stp_eprintf(v,"internal_imageable_area: page_bottom %d\n",*bottom);
    }

}

static void
canon_imageable_area(const stp_vars_t *v,   /* I */
                     int  *left,	/* O - Left position in points */
                     int  *right,	/* O - Right position in points */
                     int  *bottom,	/* O - Bottom position in points */
                     int  *top)		/* O - Top position in points */
{
  internal_imageable_area(v, 1, 0, left, right, bottom, top);
}

static void
canon_maximum_imageable_area(const stp_vars_t *v,   /* I */
                     int  *left,	/* O - Left position in points */
                     int  *right,	/* O - Right position in points */
                     int  *bottom,	/* O - Bottom position in points */
                     int  *top)		/* O - Top position in points */
{
  internal_imageable_area(v, 1, 1, left, right, bottom, top);
}

static void
canon_limit(const stp_vars_t *v,  		/* I */
	    int *width,
	    int *height,
	    int *min_width,
	    int *min_height)
{
  const canon_cap_t * caps=
    canon_get_model_capabilities(v);
  *width =	caps->max_width;
  *height =	caps->max_height;
  *min_width = 1;
  *min_height = 1;
}

/*
 * 'canon_cmd()' - Sends a command with variable args
 */
static void
canon_cmd(const stp_vars_t *v, /* I - the printer         */
	  const char *ini, /* I - 2 bytes start code  */
	  const char cmd,  /* I - command code        */
	  int  num,  /* I - number of arguments */
	  ...        /* I - the args themselves */
	  )
{
  unsigned char *buffer = stp_zalloc(num + 1);
  int i;
  va_list ap;

  if (num)
    {
      va_start(ap, num);
      for (i=0; i<num; i++)
	buffer[i]= (unsigned char) va_arg(ap, int);
      va_end(ap);
    }

  stp_zfwrite(ini,2,1,v);
  if (cmd)
    {
      stp_putc(cmd,v);
      stp_put16_le(num, v);
      if (num)
	stp_zfwrite((const char *)buffer,num,1,v);
    }
  stp_free(buffer);
}

#define PUT(WHAT,VAL,RES) stp_deprintf(STP_DBG_CANON,"canon: "WHAT\
" is %04x =% 5d = %f\" = %f mm\n",(VAL),(VAL),(VAL)/(1.*RES),(VAL)/(RES/25.4))

#define ESC28 "\033\050"
#define ESC5b "\033\133"
#define ESC40 "\033\100"

static void canon_control_cmd(const stp_vars_t*v,const char* cmd){
      canon_cmd(v,ESC5b,0x4b, 2, 0x00,0x1f);
      stp_puts("BJLSTART\nControlMode=Common\n",v);
      stp_puts(cmd,v);
      stp_putc('\n',v);
      stp_puts("BJLEND\n",v);
}


/* ESC [K --  -- reset printer:
 */
static void
canon_init_resetPrinter(const stp_vars_t *v, const canon_privdata_t *init)
{
  if ( init->caps->control_cmdlist ){
    int i=0;
    while(init->caps->control_cmdlist[i]){
      canon_control_cmd(v,init->caps->control_cmdlist[i]);
      ++i;
    }
  }
  if(!strcmp(init->slot->name,"CD"))
    canon_control_cmd(v,"MediaDetection=ON");
  canon_cmd(v,ESC5b,0x4b, 2, 0x00,0x0f);
}

/* ESC ($ -- 0x24 -- cmdSetDuplex --:
 */
static void
canon_init_setDuplex(const stp_vars_t *v, const canon_privdata_t *init)
{
  if (!(init->caps->features & CANON_CAP_DUPLEX))
    return;
  if (strncmp(init->duplex_str, "Duplex", 6)) {
    if ( !(strcmp(init->caps->name,"i860")) || !(strcmp(init->caps->name,"i865")) || !(strcmp(init->caps->name,"i950")) || !(strcmp(init->caps->name,"i960")) || !(strcmp(init->caps->name,"i990")) ) {
      /* i860, i865, i950, i960, i990 use ESC ($ command even for simplex mode */
      canon_cmd(v,ESC28,0x24,9,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00);
      return;
    }
    else
      return;
  }
  /* The same command seems to be needed for both Duplex and DuplexTumble
     no idea about the meanings of the single bytes */
  canon_cmd(v,ESC28,0x24,9,0x01,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x02);
}

/* ESC (a -- 0x61 -- cmdSetPageMode --:
 */
static void
canon_init_setPageMode(const stp_vars_t *v, const canon_privdata_t *init)
{
  if (!(init->caps->features & CANON_CAP_a))
    return;

  if (init->caps->features & CANON_CAP_a)
    canon_cmd(v,ESC28,0x61, 1, 0x01);
}

/* ESC (b -- 0x62 -- -- set data compression:
 */
static void
canon_init_setDataCompression(const stp_vars_t *v, const canon_privdata_t *init)
{
  if (!(init->caps->features & CANON_CAP_b))
    return;

  canon_cmd(v,ESC28,0x62, 1, 0x01);
}

/* ESC (c -- 0x63 -- cmdSetColor --:
 */
static void
canon_init_setColor(const stp_vars_t *v, const canon_privdata_t *init)
{
  unsigned char
    numargs, arg_63[6];

  if (!(init->caps->features & CANON_CAP_c))
    return;

  numargs = 3;
  arg_63[0] = init->caps->model_id << 4; /* MODEL_ID */

  switch ( init->caps->model_id ) {

  	case 0:			/* very old 360 dpi series: BJC-800/820 */
		break;		/*	tbd */

  	case 1:			/* 360 dpi series - BJC-4000, BJC-210, BJC-70 and their descendants */
		if (init->used_inks == CANON_INK_K)
                            arg_63[0]|= 0x01;                                        /* PRINT_COLOUR */

                  arg_63[1] = ((init->pt ? init->pt->media_code_c : 0) << 4)                /* PRINT_MEDIA */
			+ 1;	/* hardcode to High quality for now */		/* PRINT_QUALITY */

                  canon_cmd(v,ESC28,0x63, 2, arg_63[0], arg_63[1]);
		break;

	case 2:			/* are any models using this? */
		break;

	case 3:			/* 720 dpi series - BJC-3000 and descendants */
		if (init->used_inks == CANON_INK_K)
                            arg_63[0]|= 0x01;                                        /* colour mode */

                  arg_63[1] = (init->pt) ? init->pt->media_code_c : 0;                /* print media type */

                 if (!strcmp(init->caps->name,"S200")) /* S200 */
                   {
                     if ((init->mode->xdpi == 720) && (init->mode->ydpi == 720 ))
                       arg_63[2] = 1;
                     else
                       arg_63[2] = 4; /* hardcoded: quality 3  (may be 0...4) */
                     /* bidirectional is controlled via quality: 0..2 is bidi, 3 and 4 uni */
                     /* not every combination works, no idea about the principle */
                     if ( (init->mode->xdpi > 360) || (init->mode->ydpi > 360) )
                       {
                         numargs = 6;
                         arg_63[3] = 0x10; arg_63[4] = 6; arg_63[5] = 8; /* arg5 makes a vert. offset for K */
                         if (init->used_inks == CANON_INK_K)
                           arg_63[4] = 1;
                       }
                   }
		 else if (!strcmp(init->caps->name,"4550")) /* BJC-4550 */
		    {
		      numargs = 3;
		      arg_63[2] = 0; /* not used in Black and Color, no idea about PhotoColor yet */
		      arg_63[1] = init->quality;     /* hardcode to whatever this means for now; quality, apparently */
		    }
                 else
                   arg_63[2] = init->quality;        /* hardcode to whatever this means for now; quality, apparently */

                 stp_zprintf(v, "\033\050\143");
                 stp_put16_le(numargs, v);
                 stp_zfwrite((const char *)arg_63, numargs, 1, v);
		break;
  	}

  return;
}

/* ESC (d -- 0x64 -- -- set raster resolution:
 */
static void
canon_init_setResolution(const stp_vars_t *v, const canon_privdata_t *init)
{
  if (!(init->caps->features & CANON_CAP_d))
    return;

   if (strcmp(init->caps->name,"S200") || (init->mode->xdpi <= 360))
  canon_cmd(v,ESC28,0x64, 4,
	    (init->mode->ydpi >> 8 ), (init->mode->ydpi & 255),
	    (init->mode->xdpi >> 8 ), (init->mode->xdpi & 255));
   else
     if (init->mode->xdpi < 2880)
       canon_cmd(v,ESC28,0x64, 4,
         (720 >> 8), (720 & 255),
         (720 >> 8), (720 & 255));
     else
       canon_cmd(v,ESC28,0x64, 4,
         (720 >> 8), (720 & 255),
         (2880 >> 8), (2880 & 255));
  }

/* ESC (g -- 0x67 -- cmdSetPageMargins --:
 */
static void
canon_init_setPageMargins(const stp_vars_t *v, const canon_privdata_t *init)
{
  /* TOFIX: what exactly is to be sent?
   * Is it the printable length or the bottom border?
   * Is is the printable width or the right border?
   */

  int minlength= 0;
  int minwidth= 0;
  int length= init->page_height*5/36;
  int width= init->page_width*5/36;

  if (!(init->caps->features & CANON_CAP_g))
    return;

  if (minlength>length) length= minlength;
  if (minwidth>width) width= minwidth;

  canon_cmd(v,ESC28,0x67, 4, 0,
	    (unsigned char)(length),1,
	    (unsigned char)(width));

}

/* ESC (l -- 0x6c -- cmdSetTray --:
 */
static void
canon_init_setTray(const stp_vars_t *v, const canon_privdata_t *init)
{
  unsigned char
    arg_6c_1 = 0x00,
    arg_6c_2 = 0x00, /* plain paper */
    arg_6c_3 = 0x00; /* special cases like iP7100 to be handled */

  if (!(init->caps->features & CANON_CAP_l))
    return;

  arg_6c_1 = init->caps->model_id << 4;

  arg_6c_1|= (init->slot->code & 0x0f);

  /* set gap for MP710/740 if thick media selected */
  if (!strcmp(init->slot->name,"AutoThick"))
    if ( (!strcmp(init->caps->name,"PIXMA MP710")) || (!strcmp(init->caps->name,"PIXMA MP740")) ) 
      arg_6c_3 = 0x10;

  if (init->pt) arg_6c_2 = init->pt->media_code_l;
  /* select between length 2 and 3 byte variations of command */
  /*if(init->caps->model_id >= 3)*/
  if(init->caps->ESC_l_len == 3)
    canon_cmd(v,ESC28,0x6c, 3, arg_6c_1, arg_6c_2, arg_6c_3); /* 3rd arg is "gap" */
  else /* else 2 bytes---no other option for now */
    canon_cmd(v,ESC28,0x6c, 2, arg_6c_1, arg_6c_2);
}

/* ESC (m -- 0x6d --  -- :
 */
static void
canon_init_setPrintMode(const stp_vars_t *v, const canon_privdata_t *init)
{
  unsigned char
    arg_6d_1 = 0x03, /* color printhead? */
    arg_6d_2 = 0x00, /* 00=color  02=b/w */
    arg_6d_3 = 0x00, /* only 01 for bjc8200 and S200*/
                     /* S200:for envelope and t-shirt transfer = 03 */
    arg_6d_a = 0x03, /* A4 paper */
    arg_6d_b = 0x00;

  if (!(init->caps->features & CANON_CAP_m))
    return;

  arg_6d_a= canon_size_type(v,init->caps);
  if (!arg_6d_a)
    arg_6d_b= 1;

    arg_6d_1= 0x04;
  if ((!strcmp(init->caps->name,"7000")) && (init->used_inks == CANON_INK_K || init->used_inks == CANON_INK_CcMmYK || init->used_inks == CANON_INK_CcMmYyK))
    arg_6d_1= 0x03;

  if (((!strcmp(init->caps->name,"8200") || !strcmp(init->caps->name,"S200")) && init->used_inks == CANON_INK_K) || init->used_inks == CANON_INK_CMYK)
      arg_6d_1= 0x02;

  if(!strcmp(init->caps->name,"S200") && init->used_inks == CANON_INK_CMY)
      arg_6d_1= 0x02;

  if (init->used_inks == CANON_INK_K)
    arg_6d_2= 0x02;

  if (!strcmp(init->caps->name,"8200") || !strcmp(init->caps->name,"S200"))
    arg_6d_3= 0x01;

  canon_cmd(v,ESC28,0x6d,12, arg_6d_1,
	    0xff,0xff,0x00,0x00,0x07,0x00,
	    arg_6d_a,arg_6d_b,arg_6d_2,0x00,arg_6d_3);
}

/* ESC (M -- 0x4d --  -- :
 */
static void
canon_init_setESC_M(const stp_vars_t *v, const canon_privdata_t *init)
{
  if (!(init->caps->features & CANON_CAP_M))
    return;

  canon_cmd(v,ESC28,0x4d, 3, 0x00, 0x00, 0x00);
}

/* ESC (p -- 0x70 -- cmdSetPageMargins2 --:
 */
static void
canon_init_setPageMargins2(const stp_vars_t *v, const canon_privdata_t *init)
{
  unsigned char arg_70_1,arg_70_2,arg_70_3,arg_70_4;

  int border_left,border_right,border_top,border_bottom;
  int border_left2,border_top2;
  int border_right2;
  int border_bottom2;
  int area_right,area_top;

  /* TOFIX: what exactly is to be sent?
   * Is it the printable length or the bottom border?
   * Is is the printable width or the right border?
   */

  int unit = 600;
  int printable_width=  (init->page_width + 1)*5/6;
  int printable_length= (init->page_height + 1)*5/6;

  const char* input_slot = stp_get_string_parameter(v, "InputSlot");  
  int print_cd= (input_slot && (!strcmp(input_slot, "CD")));

  if (ERRPRINT) {
    stp_eprintf(v,"canon_init_setPageMargins2: borderless capability? %016lx\n", init->caps->features & CANON_CAP_BORDERLESS);
    stp_eprintf(v,"canon_init_setPageMargins2: borderless active? %d\n", stp_get_boolean_parameter(v, "FullBleed"));
  }

  if ( (init->caps->features & CANON_CAP_BORDERLESS) && 
       !(print_cd) && stp_get_boolean_parameter(v, "FullBleed") ) 
    {
      if (ERRPRINT)
	stp_eprintf(v,"canon_init_setPageMargins2: for borderless set printable length and width to 0\n");
      /* set to 0 for borderless */
      printable_width = 0;
      printable_length = 0;
    }

  arg_70_1= (printable_length >> 8) & 0xff;
  arg_70_2= (printable_length) & 0xff;
  arg_70_3= (printable_width >> 8) & 0xff;
  arg_70_4= (printable_width) & 0xff;

  if (!(init->caps->features & CANON_CAP_px) && !(init->caps->features & CANON_CAP_p))
	return;

  if ((init->caps->features & CANON_CAP_px) ) {
    /* workaround for CD writing that uses CANON_CAP_px --- fix with capabilities */
    if ( !(input_slot && !strcmp(input_slot,"CD")) || !(strcmp(init->caps->name,"PIXMA iP4600")) || !(strcmp(init->caps->name,"PIXMA iP4700")) || !(strcmp(init->caps->name,"PIXMA iP4800")) || !(strcmp(init->caps->name,"PIXMA iP4900")) || !(strcmp(init->caps->name,"PIXMA MP980")) || !(strcmp(init->caps->name,"PIXMA MP990")) || !(strcmp(init->caps->name,"PIXMA MG5200")) || !(strcmp(init->caps->name,"PIXMA MG5300")) || !(strcmp(init->caps->name,"PIXMA MG6100")) || !(strcmp(init->caps->name,"PIXMA MG6200")) || !(strcmp(init->caps->name,"PIXMA MG8100")) || !(strcmp(init->caps->name,"PIXMA MG8200")) )
      {

	/* original borders */
	border_left=init->caps->border_left;
	border_right=init->caps->border_right;
	border_top=init->caps->border_top;
	border_bottom=init->caps->border_bottom;

	if (print_cd) {
	  border_top=9;
	  border_bottom=9;
	}

	/* modified borders */
	border_left2=border_left;
	border_top2=border_top;
	border_right2=border_right;
	border_bottom2=border_bottom;

	area_right = border_left2 * unit / 72;
	area_top = border_top2 * unit / 72;

	if ( (init->caps->features & CANON_CAP_BORDERLESS) && 
	     !(print_cd) && stp_get_boolean_parameter(v, "FullBleed") ) {
	  border_left2=-8; /* -8 mini series -6 */
	  border_right2=-8; /* -8 */
	  border_top2=-6; /* -6 standard */
	  border_bottom2=-15; /* -15 standard */
	  area_right = border_left2 * unit / 72;
	  area_top = border_top2 * unit / 72;
	}

	if (ERRPRINT) {
	  stp_eprintf(v,"setPageMargins2: init->page_height = %d\n",init->page_height);
	  stp_eprintf(v,"setPageMargins2: printable_length = %d\n",printable_length);
	  stp_eprintf(v,"setPageMargins2: paper_height = %d\n",(init->page_height + border_top + border_bottom) * unit / 72);
	}


	stp_zfwrite(ESC28,2,1,v); /* ESC( */
	stp_putc(0x70,v);         /* p    */
	stp_put16_le(46, v);      /* len  */
	/* 0 for borderless, calculated otherwise */
	stp_put16_be(printable_length,v); /* Windows 698, gutenprint 570 */
	stp_put16_be(0,v);
	/* 0 for borderless, calculated otherwise */
	stp_put16_be(printable_width,v); /* Windows 352, gutenprint 342 */
	stp_put16_be(0,v);
	stp_put32_be(0,v);
	stp_put16_be(unit,v);
	
	/* depends on borderless or not: uses modified borders */
	stp_put32_be(area_right,v); /* area_right : Windows seems to use 9.6, gutenprint uses 10 */
	stp_put32_be(area_top,v);  /* area_top : Windows seems to use 8.4, gutenprint uses 15 */
	/* calculated depending on borderless or not: uses modified borders */
	stp_put32_be((init->page_width + (border_left - border_left2) + (border_right - border_right2) ) * unit / 72,v); /* area_width : Windows seems to use 352 for Tray G, gutenprint uses 340.92 */
	stp_put32_be((init->page_height + (border_top - border_top2) + (border_bottom - border_bottom2) ) * unit / 72,v); /* area_length : Windows seems to use 698.28 for Tray G, gutenprint uses 570 */
	/* 0 under all currently known circumstances */
	stp_put32_be(0,v); /* paper_right : Windows also 0 here for all Trays */
	stp_put32_be(0,v); /* paper_top : Windows also 0 here for all Trays */
	/* standard paper sizes, unchanged for borderless so use original borders */
	stp_put32_be((init->page_width + border_left + border_right) * unit / 72,v); /* paper_width : Windows 371.4, gutenprint 360.96 */
	stp_put32_be((init->page_height + border_top + border_bottom) * unit / 72,v); /* paper_height : Windows 720.96, gutenprint 600 */
	return;
      }
  }
  canon_cmd(v,ESC28,0x70, 8,
   	      arg_70_1, arg_70_2, 0x00, 0x00,
	      arg_70_3, arg_70_4, 0x00, 0x00);
}

/* ESC (P -- 0x50 -- unknown -- :
    pt = stp_get_papersize_by_name(media_size);
   seems to set media and page information. Different byte lengths depending on printer model. */
static void
canon_init_setESC_P(const stp_vars_t *v, const canon_privdata_t *init)
{
  unsigned char arg_ESCP_1, arg_ESCP_2;
  if(!(init->caps->features & CANON_CAP_P))
    return;

  arg_ESCP_1 = (init->pt) ? canon_size_type(v,init->caps): 0x03;
  arg_ESCP_2 = (init->pt) ? init->pt->media_code_P: 0x00;

  /* workaround for CD media */

  if ( (arg_ESCP_2 == 0x1f) || ( arg_ESCP_2 == 0x20) ) {
    if ( arg_ESCP_1 == 0x53 ) {
      /* Tray G as default */
      arg_ESCP_1 = 0x53;
      /* Custom CD tray */
      if ( !(strcmp(init->caps->name,"i865")) || !(strcmp(init->caps->name,"PIXMA MP710")) || !(strcmp(init->caps->name,"PIXMA MP740")) || !(strcmp(init->caps->name,"PIXMA MP900")) ) {
	arg_ESCP_1 = 0x35;
      }
      /* Tray A */
      if ( !(strcmp(init->caps->name,"PIXMA iP9910")) ) {
	arg_ESCP_1 = 0x3f;
      }
      /* Tray B */
      if ( !(strcmp(init->caps->name,"PIXMA MP750")) || !(strcmp(init->caps->name,"PIXMA MP760")) || !(strcmp(init->caps->name,"PIXMA MP770")) || !(strcmp(init->caps->name,"PIXMA MP780")) || !(strcmp(init->caps->name,"PIXMA MP790")) || !(strcmp(init->caps->name,"PIXMA iP3000")) || !(strcmp(init->caps->name,"PIXMA iP3100")) || !(strcmp(init->caps->name,"PIXMA iP4000")) || !(strcmp(init->caps->name,"PIXMA iP4100")) || !(strcmp(init->caps->name,"PIXMA iP5000")) || !(strcmp(init->caps->name,"PIXMA iP6000")) || !(strcmp(init->caps->name,"PIXMA iP6100")) || !(strcmp(init->caps->name,"PIXMA iP7100")) || !(strcmp(init->caps->name,"PIXMA iP8100")) || !(strcmp(init->caps->name,"PIXMA iP8500")) || !(strcmp(init->caps->name,"PIXMA iP8600")) ) {
	arg_ESCP_1 = 0x40;
      }
      /* Tray C */
      if ( !(strcmp(init->caps->name,"PIXMA MP950")) || !(strcmp(init->caps->name,"PIXMA iP4200")) || !(strcmp(init->caps->name,"PIXMA iP5200")) || !(strcmp(init->caps->name,"PIXMA iP6700")) || !(strcmp(init->caps->name,"PIXMA iP7500")) ) {
	arg_ESCP_1 = 0x4a;
      }
      /* Tray D */
      if ( !(strcmp(init->caps->name,"PIXMA MP500")) || !(strcmp(init->caps->name,"PIXMA MP530")) || !(strcmp(init->caps->name,"PIXMA MP800")) || !(strcmp(init->caps->name,"PIXMA MP830")) ) {
	arg_ESCP_1 = 0x4b;
      }
      /* Tray E */
      if ( !(strcmp(init->caps->name,"PIXMA Pro9000")) || !(strcmp(init->caps->name,"PIXMA Pro9002")) || !(strcmp(init->caps->name,"PIXMA Pro9500")) || !(strcmp(init->caps->name,"PIXMA Pro95002")) ) {
	arg_ESCP_1 = 0x4c;
      }
      /* Tray F */
      if ( !(strcmp(init->caps->name,"PIXMA MP600")) || !(strcmp(init->caps->name,"PIXMA MP610")) || !(strcmp(init->caps->name,"PIXMA MP810")) || !(strcmp(init->caps->name,"PIXMA MP960")) || !(strcmp(init->caps->name,"PIXMA MP970")) || !(strcmp(init->caps->name,"PIXMA MX850")) || !(strcmp(init->caps->name,"PIXMA iP4300")) || !(strcmp(init->caps->name,"PIXMA iP4500")) || !(strcmp(init->caps->name,"PIXMA iP5300")) ) {
	arg_ESCP_1 = 0x51;
      }
      /* Tray G from iP4800 onwards */
      if ( !(strcmp(init->caps->name,"PIXMA iP4800")) || !(strcmp(init->caps->name,"PIXMA iP4900")) || !(strcmp(init->caps->name,"PIXMA MG5200")) || !(strcmp(init->caps->name,"PIXMA MG5300")) || !(strcmp(init->caps->name,"PIXMA MG6100")) || !(strcmp(init->caps->name,"PIXMA MG6200")) || !(strcmp(init->caps->name,"PIXMA MG8100")) || !(strcmp(init->caps->name,"PIXMA MG8200")) ) {
	arg_ESCP_1 = 0x56;
      }
    }
  }
      /*  850i:  CD Tray custom: none --- no ESC (P */
      /*  865i:  CD Tray custom: 0x35               */
      /* MP500:  CD Tray D     : 0x4b               */
      /* MP530:  CD Tray D     : 0x4b               */
      /* MP600:  CD Tray F     : 0x51               */
      /* MP610:  CD Tray F     : 0x51               */
      /* MP630:  CD Tray G     : 0x53               */
      /* MP640:  CD Tray G     : 0x53               */
      /* MP700:  CD tray custom: none --- no ESC (P */
      /* MP710:  CD tray custom: 0x35               */
      /* MP730:  CD tray custom: none --- no ESC (P */
      /* MP740:  CD tray custom: 0x35               */
      /* MP750:  CD Tray B     : 0x40               */
      /* MP760:  CD Tray B     : 0x40               */
      /* MP770:  CD Tray B     : 0x40               */
      /* MP780:  CD Tray B     : 0x40               */
      /* MP790:  CD Tray B     : 0x40               */
      /* MP800:  CD Tray D     : 0x4b               */
      /* MP810:  CD Tray F     : 0x51               */
      /* MP830:  CD Tray D     : 0x4b               */
      /* MP900:  CD Tray custom: 0x35               */
      /* MP950:  CD Tray C     : 0x4a               */
      /* MP960:  CD Tray F     : 0x51               */
      /* MP970:  CD Tray F     : 0x51               */
      /* MP980:  CD Tray G     : 0x53               */
      /* MP990:  CD Tray G     : 0x53               */
      /* MX850:  CD Tray F     : 0x51               */
      /* iP3000: CD Tray B     : 0x40               */
      /* iP3100: CD Tray B     : 0x40               */
      /* iP4000: CD Tray B     : 0x40               */
      /* iP4100: CD Tray B     : 0x40               */
      /* iP4200: CD Tray C     : 0x4a               */
      /* iP4300: CD Tray F     : 0x51               */
      /* iP4500: CD Tray F     : 0x51               */
      /* iP4600: CD Tray G     : 0x53               */
      /* iP4700: CD Tray G     : 0x53               */
      /* iP4800: CD Tray G     : 0x56               */
      /* iP4900: CD Tray G     : 0x56               */
      /* iP5000: CD Tray B     : 0x40               */
      /* iP5200: CD Tray C     : 0x4a               */
      /* iP5300: CD Tray F     : 0x51               */
      /* iP6000D:CD Tray B     : 0x40               */
      /* iP6100D:CD Tray B     : 0x40               */
      /* iP6700D:CD Tray C     : 0x4a               */
      /* iP7100: CD Tray B     : 0x40               */
      /* iP7500: CD Tray C     : 0x4a               */
      /* iP8100: CD Tray B     : 0x40               */
      /* iP8500 :CD Tray B     : 0x40               */
      /* iP8600: CD Tray B     : 0x40               */
      /* iP9910: CD Tray A     : 0x3f               */
      /* MG5200: CD Tray G     : 0x56               */
      /* MG5300: CD Tray G     : 0x56               */
      /* MG6100: CD Tray G     : 0x56               */
      /* MG6200: CD Tray G     : 0x56               */
      /* MG8100: CD Tray G     : 0x56               */
      /* MG8200: CD Tray G     : 0x56               */
      /* pro9000:CD Tray E     : 0x4c               */
      /* pro9000mk2:CD Tray E  : 0x4c               */
      /* pro9500:CD Tray E     : 0x4c               */
      /* pro9500mk2:CD Tray E  : 0x4c               */
      /* PRO-1:  CD Tray H     : 0x57               */



  /* workaround for FineArt media having same size as non-FineArt media */

      /* MP950:  FineArtA4     : 0x42               */
      /* MP960:  FineArtA4     : 0x42               */
      /* MP970:  FineArtA4     : 0x42               */
      /* MP980:  FineArtA4     : 0x42               */
      /* MP990:  FineArtA4     : 0x42               */
      /* MX7600: FineArtA4     : 0x42               */
      /* iP6700D:FineArtA4     : 0x42               */
      /* iP7100: FineArtA4     : 0x42               */
      /* iP7500: FineArtA4     : 0x42               */
      /* iP8100: FineArtA4     : 0x42               */
      /* iP8600: FineArtA4     : 0x42               */
      /* iP9910: FineArtA4     : 0x42               */
      /* iX7000: FineArtA4     : 0x42               */
      /* MG6100: FineArtA4     : 0x42               */
      /* MG6200: FineArtA4     : 0x42               */
      /* MG8100: FineArtA4     : 0x42               */
      /* MG8200: FineArtA4     : 0x42               */
      /* pro9000:FineArtA4     : 0x4d               */
      /* pro9000mk2:FineArtA4  : 0x4d               */
      /* pro9500:FineArtA4     : 0x4d               */
      /* pro9500mk2:FineArtA4  : 0x4d               */
      /* PRO-1:  FineArtA4     : 0x4d               */

  /* iP7100 is an exception needing yet another papersize code */
  if ( (arg_ESCP_2 == 0x28) || ( arg_ESCP_2 == 0x29) || (arg_ESCP_2 ==  0x2c) || (arg_ESCP_2 == 0x31) ) {
    /* A4 */
    if ( arg_ESCP_1 == 0x03 ) {
      /* default */
      arg_ESCP_1 = 0x4d;
      if ( !(strcmp(init->caps->name,"PIXMA MP950")) || !(strcmp(init->caps->name,"PIXMA MP960")) || !(strcmp(init->caps->name,"PIXMA MP970")) || !(strcmp(init->caps->name,"PIXMA MP980")) || !(strcmp(init->caps->name,"PIXMA MP990")) || !(strcmp(init->caps->name,"PIXMA MX7600")) || !(strcmp(init->caps->name,"PIXMA iP6700")) || !(strcmp(init->caps->name,"PIXMA iP7100")) || !(strcmp(init->caps->name,"PIXMA iP7500")) || !(strcmp(init->caps->name,"PIXMA iP8100")) || !(strcmp(init->caps->name,"PIXMA iP8600")) || !(strcmp(init->caps->name,"PIXMA iP9910")) || !(strcmp(init->caps->name,"PIXMA iX7000")) || !(strcmp(init->caps->name,"PIXMA MG6100")) || !(strcmp(init->caps->name,"PIXMA MG8200")) || !(strcmp(init->caps->name,"PIXMA MG8100")) || !(strcmp(init->caps->name,"PIXMA MG8200")) ) {
	arg_ESCP_1 = 0x42;
      }
    }
    /* A3 */
    if ( arg_ESCP_1 == 0x05 ) {
      arg_ESCP_1 = 0x4e;
      if ( !(strcmp(init->caps->name,"PIXMA MP950")) || !(strcmp(init->caps->name,"PIXMA MP960")) || !(strcmp(init->caps->name,"PIXMA MP970")) || !(strcmp(init->caps->name,"PIXMA MP980")) || !(strcmp(init->caps->name,"PIXMA MP990")) || !(strcmp(init->caps->name,"PIXMA MX7600")) || !(strcmp(init->caps->name,"PIXMA iP6700")) || !(strcmp(init->caps->name,"PIXMA iP7100")) || !(strcmp(init->caps->name,"PIXMA iP7500")) || !(strcmp(init->caps->name,"PIXMA iP8100")) || !(strcmp(init->caps->name,"PIXMA iP8600")) || !(strcmp(init->caps->name,"PIXMA iP9910")) || !(strcmp(init->caps->name,"PIXMA iX7000")) || !(strcmp(init->caps->name,"PIXMA MG6100")) || !(strcmp(init->caps->name,"PIXMA MG8200")) || !(strcmp(init->caps->name,"PIXMA MG8100")) || !(strcmp(init->caps->name,"PIXMA MG8200")) ) {
	arg_ESCP_1 = 0x43;
      }
    }
    /* Letter */
    if ( arg_ESCP_1 == 0x0d ) {
      arg_ESCP_1 = 0x4f;
      if ( !(strcmp(init->caps->name,"PIXMA MP950")) || !(strcmp(init->caps->name,"PIXMA MP960")) || !(strcmp(init->caps->name,"PIXMA MP970")) || !(strcmp(init->caps->name,"PIXMA MP980")) || !(strcmp(init->caps->name,"PIXMA MP990")) || !(strcmp(init->caps->name,"PIXMA MX7600")) || !(strcmp(init->caps->name,"PIXMA iP6700")) || !(strcmp(init->caps->name,"PIXMA iP7100")) || !(strcmp(init->caps->name,"PIXMA iP7500")) || !(strcmp(init->caps->name,"PIXMA iP8100")) || !(strcmp(init->caps->name,"PIXMA iP8600")) || !(strcmp(init->caps->name,"PIXMA iP9910")) || !(strcmp(init->caps->name,"PIXMA iX7000")) || !(strcmp(init->caps->name,"PIXMA MG6100")) || !(strcmp(init->caps->name,"PIXMA MG8200")) || !(strcmp(init->caps->name,"PIXMA MG8100")) || !(strcmp(init->caps->name,"PIXMA MG8200")) ) {
	arg_ESCP_1 = 0x44;
      }
    }
  }

  if ( init->caps->ESC_P_len == 8 ) /* support for new devices from 2012. TODO: check if XML contents are identical to 6-byte devices */
    {/* the 4th of the 6 bytes is the media type. 2nd byte is media size. Both read from canon-media array. */

      /* arg_ESCP_1 = 0x03; */ /* A4 size */
      /* arg_ESCP_2 = 0x00; */ /* plain media */
      /*                             size                media             */
      canon_cmd( v,ESC28,0x50,8,0x00,arg_ESCP_1,0x00,arg_ESCP_2,0x01,0x00,0x01,0x00);
    }
  else if ( init->caps->ESC_P_len == 6 ) /* first devices with XML header and ender */
    {/* the 4th of the 6 bytes is the media type. 2nd byte is media size. Both read from canon-media array. */

      /* arg_ESCP_1 = 0x03; */ /* A4 size */
      /* arg_ESCP_2 = 0x00; */ /* plain media */
      /*                             size                media             */
      canon_cmd( v,ESC28,0x50,6,0x00,arg_ESCP_1,0x00,arg_ESCP_2,0x01,0x00);
    }
  else if ( init->caps->ESC_P_len == 4 )  {/* 4 bytes */
    /*                             size            media       */
    canon_cmd( v,ESC28,0x50,4,0x00,arg_ESCP_1,0x00,arg_ESCP_2 );
  }
  else if ( init->caps->ESC_P_len == 2 )  {
    /* 2 bytes only */
      canon_cmd( v,ESC28,0x50,2,0x00,arg_ESCP_1 );
    }	
  else /* error in definition */
    stp_deprintf(STP_DBG_CANON,"SEVERE BUG IN print-canon.c::canon_init_setESC_P() "
		 "ESC_P_len=%d!!\n",init->caps->ESC_P_len);
}

/* ESC (S -- 0x53 -- unknown -- :
   Required by iP90/iP90v and iP100 printers.
 */
static void
canon_init_setESC_S(const stp_vars_t *v, const canon_privdata_t *init)
{
  unsigned char arg_ESCS_01,arg_ESCS_04,arg_ESCS_09,arg_ESCS_11;

  if (!(init->caps->features & CANON_CAP_S))
    return;

  if (!(init->mode->flags & MODE_FLAG_S))
    return;

  /* iP90 defaults: based on non-photo media */
  arg_ESCS_01 = 0x01;
  arg_ESCS_04 = 0xff;
  arg_ESCS_09 = 0x1a;
  arg_ESCS_11 = 0x68;
  
  /* hard-coded for different media, color and  quality settings */
  /* iP90 bytes 1,4,9 and 11 vary */
  if ( !(strcmp(init->caps->name,"PIXMA iP90")) ) {
    if ( !strcmp(init->mode->name,"600x600dpi_high2") || !strcmp(init->mode->name,"600x600dpi_high4") ) {
      /* if inkset is color then set special bytes, else leave default.
	 Note: in this case the mode only has CMYK, mono is a different mode.
      */
      if (init->used_inks == CANON_INK_CMYK) {
	arg_ESCS_01 = 0xc1;
	arg_ESCS_04 = 0xf1;
	arg_ESCS_09 = 0x50;
	arg_ESCS_11 = 0x28;
      }
    } else if ( !strcmp(init->mode->name,"300x300dpi_draft") ) {
      /* set regardless of inkset */
      arg_ESCS_09 = 0x02;
      arg_ESCS_11 = 0x08;
    } else if ( !strcmp(init->mode->name,"600x600dpi_draft2") ) {
      /* if inkset is color then set special bytes, else leave default */
      if (init->used_inks == CANON_INK_CMYK) {
	arg_ESCS_09 = 0x0a;
	arg_ESCS_11 = 0x28;
      }
    } else if ( !strcmp(init->mode->name,"600x600dpi_photohigh") || !strcmp(init->mode->name,"600x600dpi_photo") || !strcmp(init->mode->name,"600x600dpi_photodraft") ) {
      /* almost all photo media need (same) changes from defaults */
      /* exception: "600x600dpi_photohigh2" no ESC (S command */
      /* exception: "600x600dpi_tshirt" no ESC (S command */
      arg_ESCS_01 = 0xc1;
      arg_ESCS_04 = 0xf0;
      arg_ESCS_09 = 0x50;
      arg_ESCS_11 = 0x28;
    }
  }
  else if ( !(strcmp(init->caps->name,"PIXMA iP100")) ) {
    /* iP100 bytes 9 and 11 vary */       
    if ( !strcmp(init->mode->name,"300x300dpi_draft") ) {
      /* set regardless of inkset */
      arg_ESCS_09 = 0x02;
      arg_ESCS_11 = 0x08;
    } else if  ( !strcmp(init->mode->name,"600x600dpi_photohigh2") || !strcmp(init->mode->name,"600x600dpi_photohigh") || !strcmp(init->mode->name,"600x600dpi_photo2") || !strcmp(init->mode->name,"600x600dpi_photo") || !strcmp(init->mode->name,"600x600dpi_tshirt") ) {
      /* all photo media need (same) changes from defaults */
      arg_ESCS_09 = 0x0a;
      arg_ESCS_11 = 0x28;
    }
  }

      canon_cmd(v,ESC28,0x53,54,arg_ESCS_01,0x02,0xff,arg_ESCS_04,0x41,0x02,0x00,0x01,arg_ESCS_09,0x00,arg_ESCS_11,0x00,0x01,0x01,0x03,0x02,0x01,0x01,0x01,0x03,0x02,0x00,0x07,0x06,0x02,0x01,0x02,0x04,0x04,0x04,0x05,0x06,0x08,0x08,0x08,0x0a,0x0a,0x09,0x00,0x03,0x02,0x01,0x01,0x01,0x01,0x01,0x06,0x02,0x02,0x02,0x03,0x04,0x05,0x06);

}


/* ESC (T -- 0x54 -- setCartridge -- :
 */
static void
canon_init_setCartridge(const stp_vars_t *v, const canon_privdata_t *init)
{
  const char *ink_set;

  if (!(init->caps->features & CANON_CAP_T))
    return;

  ink_set = stp_get_string_parameter(v, "InkSet");

  if (ink_set && !(strcmp(ink_set,"Both"))) {
    if ( !(strcmp(init->caps->name,"PIXMA iP90")) || !(strcmp(init->caps->name,"PIXMA iP100")) ) {
      canon_cmd(v,ESC28,0x54,3,0x02,0x00,0x00); /* default for iP90, iP100 */
    } 
    else if ( !(strcmp(init->caps->name,"PIXMA iP6210")) ) {
      canon_cmd(v,ESC28,0x54,3,0x03,0x06,0x06); /* default for iP6210D, iP6220D, iP6310D */
      /* both:  0x3 0x6 0x6 */
      /* color: 0x3 0x1 0x1 */
    }
    else {
      canon_cmd(v,ESC28,0x54,3,0x03,0x04,0x04); /* default: both cartridges */
    }
  }
  else if (ink_set && !(strcmp(ink_set,"Black"))) {
    if ( !(strcmp(init->caps->name,"PIXMA iP90")) || !(strcmp(init->caps->name,"PIXMA iP100")) ) {
      canon_cmd(v,ESC28,0x54,3,0x02,0x00,0x00); /* default for iP90, iP100 */
    } 
    else if ( !(strcmp(init->caps->name,"PIXMA iP6210")) ) {
	canon_cmd(v,ESC28,0x54,3,0x03,0x06,0x06); /* default for iP6210D, iP6220D, iP6310D */
	/* both:  0x3 0x6 0x6 */
	/* color: 0x3 0x1 0x1 */
	/* workaround since does not have black option */
    }
    else {
      canon_cmd(v,ESC28,0x54,3,0x03,0x02,0x02); /* default: black cartridge */
    }
  }
  else if (ink_set && !(strcmp(ink_set,"Color"))) {
    if ( !(strcmp(init->caps->name,"PIXMA iP90")) || !(strcmp(init->caps->name,"PIXMA iP100")) ) {
      canon_cmd(v,ESC28,0x54,3,0x02,0x00,0x01); /* composite for iP90, iP100 */
      /* black save     : 2 1 0 for selected plain (600dpi std) modes, rest remain 2 0 0 */
      /* composite black: 2 0 1 for selected plain (600dpi std & draft) modes, rest remain 2 0 0 */
      /* both above set : AND of bytes above */
    } 
    else if ( !(strcmp(init->caps->name,"PIXMA iP6210")) ) {
      canon_cmd(v,ESC28,0x54,3,0x03,0x01,0x01); /* default for iP6210D, iP6220D, iP6310D */
      /* both:  0x3 0x6 0x6 */
      /* color: 0x3 0x1 0x1 */
    }
    else {
      canon_cmd(v,ESC28,0x54,3,0x03,0x01,0x01); /* default: color cartridges */
    }
  }
  else {
    canon_cmd(v,ESC28,0x54,3,0x03,0x04,0x04); /* default: both cartridges */
  }
}

/* ESC (q -- 0x71 -- setPageID -- :
 */
static void
canon_init_setPageID(const stp_vars_t *v, const canon_privdata_t *init)
{
  if (!(init->caps->features & CANON_CAP_q))
    return;

  canon_cmd(v,ESC28,0x71, 1, 0x01);
}

/* ESC (r -- 0x72 --  -- :
 */
static void
canon_init_setX72(const stp_vars_t *v, const canon_privdata_t *init)
{
  if ( !( (init->caps->features & CANON_CAP_r)
         || (init->caps->features & CANON_CAP_rr) ) )
    return;

  if ( (init->caps->features & CANON_CAP_r)
       || (init->caps->features & CANON_CAP_rr) )
    if  (init->caps->ESC_r_arg != 0) /* only output arg if non-zero */
      canon_cmd(v,ESC28,0x72, 1, init->caps->ESC_r_arg); /* whatever for - 8200/S200 need it */
  if (init->caps->features & CANON_CAP_rr) {
    if ( !(strcmp(init->caps->name,"S200")) ) {
      canon_cmd(v,ESC28,0x72, 3, 0x63, 1, 0); /* whatever for - S200 needs it */
      /* probably to set the print direction of the head */
    }
    else if ( !(strcmp(init->caps->name,"S820")) || !(strcmp(init->caps->name,"S900")) || !(strcmp(init->caps->name,"i950")) || !(strcmp(init->caps->name,"i960")) || !(strcmp(init->caps->name,"i9100")) || !(strcmp(init->caps->name,"i9900")) || !(strcmp(init->caps->name,"PIXMA iP7100")) || !(strcmp(init->caps->name,"PIXMA iP8100")) || !(strcmp(init->caps->name,"PIXMA iP8500")) || !(strcmp(init->caps->name,"PIXMA iP8600")) || !(strcmp(init->caps->name,"PIXMA iP9910")) || !(strcmp(init->caps->name,"PIXMA MP900")) || !(strcmp(init->caps->name,"PIXMA Pro9000")) || !(strcmp(init->caps->name,"PIXMA Pro9002")) || !(strcmp(init->caps->name,"PIXMA Pro9500")) || !(strcmp(init->caps->name,"PIXMA Pro9502")) ) {
      canon_cmd(v,ESC28,0x72, 2, 0x62, 0); /* 2 bytes */
    }
    /* CD mode only */
    else if ( (init->mode->flags & MODE_FLAG_CD) && (!(strcmp(init->caps->name,"PIXMA iP4600")) || !(strcmp(init->caps->name,"PIXMA iP4700")) || !(strcmp(init->caps->name,"PIXMA MP980")) || !(strcmp(init->caps->name,"PIXMA MP990")) ) ) {
      canon_cmd(v,ESC28,0x72, 1, 0x65);
    }
    /* CD mode only */
    else if ( (init->mode->flags & MODE_FLAG_CD) && ( !(strcmp(init->caps->name,"PIXMA iP4800")) || !(strcmp(init->caps->name,"PIXMA MG6100")) || !(strcmp(init->caps->name,"PIXMA MG8100")) ) ) {
      canon_cmd(v,ESC28,0x72, 1, 0x68);
    }
    /* CD mode only -- no ESC (r at all otherwise */
    else if ( (init->mode->flags & MODE_FLAG_CD) && ( !(strcmp(init->caps->name,"PIXMA iP4900")) || !(strcmp(init->caps->name,"PIXMA MG5200")) || !(strcmp(init->caps->name,"PIXMA MG5300")) || !(strcmp(init->caps->name,"PIXMA MG6200")) || !(strcmp(init->caps->name,"PIXMA MG8200")) ) ) {
      canon_cmd(v,ESC28,0x72, 1, 0x68);
    }
    /* other cases here */
  }
}

/* ESC (r -- 0x72 -- ??? set direction ??? -- :
   only works if quality = 01  (S200) */
static void
canon_set_X72(const stp_vars_t *v, int x72arg)
{
  canon_cmd(v,ESC28,0x72, 3, 0x63, x72arg, 0);
}

/* ESC (t -- 0x74 -- cmdSetImage --:
 */
static void
canon_init_setImage(const stp_vars_t *v, const canon_privdata_t *init)
{
  unsigned char
    arg_74_1 = 0x01, /* 1 bit per pixel */
    arg_74_2 = 0x00, /*  */
    arg_74_3 = 0x01; /* 01 <= 360 dpi    09 >= 720 dpi */

  if (!(init->caps->features & CANON_CAP_t))
    return;

  if(init->mode->flags & MODE_FLAG_EXTENDED_T)  /*code requires extended mode settings*/
  {
    int i;
    int length = init->mode->num_inks*3 + 3;
    unsigned char* buf = stp_zalloc(length);
    buf[0]=0x80;
    if(init->mode->flags & MODE_FLAG_PRO){
        buf[1]=0x90; /* was 0x10, but this should probably be 0x90 */
    	buf[2]=0x4;
    }else if(init->mode->flags & MODE_FLAG_IP8500){
    	buf[1]=0x00;
    	buf[2]=0x01;
    }else if(init->mode->flags & MODE_FLAG_MP130){
    	buf[1]=0x04;
    	buf[2]=0x01;
    }else if(init->mode->flags & MODE_FLAG_MP360){
    	buf[1]=0x84;
    	buf[2]=0x01;
    }else{
    	buf[1]=0x80;
    	buf[2]=0x01;
    }
    for(i=0;i<init->mode->num_inks;i++){
        if(init->mode->inks[i].channel != 0){ /* 0 means ink is used in gutenprint for sub-channel setup but not intended for printer */
          if(init->mode->inks[i].ink->flags & INK_FLAG_5pixel_in_1byte)
            buf[3+i*3+0]=(1<<5)|init->mode->inks[i].ink->bits; /*info*/
           /*else if(init->mode->inks[i].ink->flags & INK_FLAG_lowresmode)
             {
               buf[3+i*3+1]=0x01;
               buf[3+i*3+0]=init->mode->inks[i].ink->bits;
             }*/
          else
            buf[3+i*3+0]=init->mode->inks[i].ink->bits;

          /* workaround for now on the 4-4 inkset and others */
          /*if (init->mode->inks[i].ink->bits == 4)
            buf[3+i*3+2] = 0x04;*/
          /*else if (init->mode->inks[i].ink->bits == 2)
            buf[3+i*3+2] = 0x04;*/
          /*else if (init->mode->inks[i].ink->bits == 1)
            buf[3+i*3+2] = 0x02;*/
	  /*else*/ /* normal operation */
	    buf[3+i*3+2]= init->mode->inks[i].ink->numsizes+1;/*level*/
          /*else
            buf[3+i*3+2] = 0x00;*/
          /* this should show that there is an error */
       }
    }
    stp_zfwrite(ESC28,2,1,v);
    stp_putc(0x74,v);
    stp_put16_le(length,v);
    stp_zfwrite((char*)buf,length,1,v);
    stp_free(buf);
    return;
  }

  /* other models mostly hardcoded stuff not really understood ;( */
  if (!strcmp(init->caps->name,"S200")) /* 1 bit per pixel (arg 4,7,10,13); */
                               /* 2 level per pixel (arg 6,9,12,15) for each color */
                               /* though we print only 1bit/pixel - but this is how */
                               /* the windows driver works */
  {
    canon_cmd(v,ESC28,0x74, 30, 0x80, 4, 1, 1, 0, 2, 1, 0, 2, 1, 0, 2, 1, 0, 2,\
              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
    return;
  }

  if (init->mode->xdpi==1440) arg_74_2= 0x04;
  if (init->mode->ydpi>=720)  arg_74_3= 0x09;

  if (init->mode->inks[0].ink->bits>1) {
    arg_74_1= 0x02;
    arg_74_2= 0x80;
    arg_74_3= 0x09; /* default for most media */
    /* FIXME: (Gernot) below must be corrected I think, since CMY is
       not a function of the cartridge but of the driver selection of
       which logical inks get sent to the printer. So here the
       printers that use this should be enumerated, rather than a
       generic condition based on CANON_INK_CMY */
    if (init->used_inks == CANON_INK_CMY) arg_74_3= 0x02; /* for BC-06 cartridge!!! */
    /* example of better way: for BJC-3000 series */
    if  (!strcmp(init->caps->name,"3000") || !strcmp(init->caps->name,"4300")) {
      /* but if photo cartridge selection, set differently again */
      if (init->mode->flags & MODE_FLAG_PHOTO)
	arg_74_3= 0x0a;
      /* T-Shirt (3), Backprint Film (3) or Transparencies (2) */
      else if ((init->pt->media_code_c==2) || (init->pt->media_code_c==3))
	arg_74_3= 0x01;
      else
	/* other media */
	arg_74_3= 0x09; /* return to default after broken code above */
    }
  }

  /* workaround for the bjc8200 in 6color mode - not really understood */
  if (!strcmp(init->caps->name,"8200")) {
    if (init->used_inks == CANON_INK_CcMmYK) {
      arg_74_1= 0xff;
      arg_74_2= 0x90;
      arg_74_3= 0x04;
      if (init->mode->ydpi>600)  arg_74_3= 0x09;
    } else {
      arg_74_1= 0x01;
      arg_74_2= 0x00;
      arg_74_3= 0x01;
      if (init->mode->ydpi>600)  arg_74_3= 0x09;
    }
  }

  canon_cmd(v,ESC28,0x74, 3, arg_74_1, arg_74_2, arg_74_3);
}

/* ESC (I (J (L 
 */
static void
canon_init_setMultiRaster(const stp_vars_t *v, const canon_privdata_t *init){
  
  int i; /* introduced for channel counting */
  char* raster_channel_order; /* introduced for channel counting */

  if(!(init->caps->features & CANON_CAP_I))
	return;

  canon_cmd(v,ESC28,0x49, 1, 0x1);  /* enable MultiLine Raster? */
  /* canon_cmd(v,ESC28,0x4a, 1, init->caps->raster_lines_per_block); */
  canon_cmd(v,ESC28,0x4a, 1, init->mode->raster_lines_per_block);    /* set number of lines per raster block */
 
  /* set the color sequence */ 
  stp_zfwrite("\033(L", 3, 1, v);
  stp_put16_le(init->num_channels, v);
  /* add an exception here to add 0x60 of cmy channels for those printers/modes that require it */
  raster_channel_order=init->channel_order;
  if ( !(strcmp(init->caps->name,"PIXMA MP140")) || !(strcmp(init->caps->name,"PIXMA MP150")) || !(strcmp(init->caps->name,"PIXMA MP160")) || !(strcmp(init->caps->name,"PIXMA MP170")) || !(strcmp(init->caps->name,"PIXMA MP180")) || !(strcmp(init->caps->name,"PIXMA MP190")) || !(strcmp(init->caps->name,"PIXMA MP210")) || !(strcmp(init->caps->name,"PIXMA MP220")) || !(strcmp(init->caps->name,"PIXMA MP240")) || !(strcmp(init->caps->name,"PIXMA MP250")) || !(strcmp(init->caps->name,"PIXMA MP270")) || !(strcmp(init->caps->name,"PIXMA MP280")) || !(strcmp(init->caps->name,"PIXMA MP450")) || !(strcmp(init->caps->name,"PIXMA MP460")) || !(strcmp(init->caps->name,"PIXMA MP470")) || !(strcmp(init->caps->name,"PIXMA MP480")) || !(strcmp(init->caps->name,"PIXMA MP490")) || !(strcmp(init->caps->name,"PIXMA MP495")) || !(strcmp(init->caps->name,"PIXMA MX300")) || !(strcmp(init->caps->name,"PIXMA MX310")) || !(strcmp(init->caps->name,"PIXMA MX330")) || !(strcmp(init->caps->name,"PIXMA MX340")) || !(strcmp(init->caps->name,"PIXMA MX350")) || !(strcmp(init->caps->name,"PIXMA MX360"))  || !(strcmp(init->caps->name,"PIXMA MX370")) || !(strcmp(init->caps->name,"PIXMA MX410")) || !(strcmp(init->caps->name,"PIXMA MX510")) || !(strcmp(init->caps->name,"PIXMA iP2700")) || !(strcmp(init->caps->name,"PIXMA MG2100")) )
    {
      /* if cmy there, add 0x60 to each --- all modes using cmy require it */
      for(i=0;i<init->num_channels;i++){
	switch(init->channel_order[i]){
	case 'c':raster_channel_order[i]+=0x60; break;;
	case 'm':raster_channel_order[i]+=0x60; break;;
	case 'y':raster_channel_order[i]+=0x60; break;;
	}
      }
      /* Gernot: debug */
      /* if CMY there, add 0x80 to each to change to cmy+0x60 */
      /*     for(i=0;i<init->num_channels;i++){
	switch(init->channel_order[i]){
	case 'C':raster_channel_order[i]+=0x80; break;;
	case 'M':raster_channel_order[i]+=0x80; break;;
	case 'Y':raster_channel_order[i]+=0x80; break;;
	}
	}*/
      stp_zfwrite((const char *)raster_channel_order,init->num_channels, 1, v);
    }
  /* note these names are from canon-printers.h, only separate driver strings are required */
  else if ( !(strcmp(init->caps->name,"PIXMA iP6210")) ) {
    /* if cmy there, add 0x60 to each --- only some modes using cmy require it */
    /* case one: all modes with only cmy */
    if (init->num_channels==3) {
      for(i=0;i<init->num_channels;i++){
	switch(init->channel_order[i]){
	case 'c':raster_channel_order[i]+=0x60; break;;
	case 'm':raster_channel_order[i]+=0x60; break;;
	case 'y':raster_channel_order[i]+=0x60; break;;
	}
      }
    }
    /* case two: CMYcmy modes, but not CMYkcm modes */
    else if ( (init->num_channels==6) && (init->used_inks==CANON_INK_CMY) ) {
      for(i=0;i<init->num_channels;i++){
	switch(init->channel_order[i]){
	case 'c':raster_channel_order[i]+=0x60; break;;
	case 'm':raster_channel_order[i]+=0x60; break;;
	case 'y':raster_channel_order[i]+=0x60; break;;
	}
      }
    }
    /* case three: CMYkm modes with 0x80 to subtract from all inks with 2 or 8 bits */
    else if ( (init->num_channels==6) && (init->used_inks==CANON_INK_CcMmYK) && ((init->mode->inks[0].ink->bits==2) || (init->mode->inks[0].ink->bits==8)) ) {
      for(i=0;i<init->num_channels;i++){
	switch(init->channel_order[i]){
	case 'C':raster_channel_order[i]+=0x80; break;;
	case 'M':raster_channel_order[i]+=0x80; break;;
	case 'Y':raster_channel_order[i]+=0x80; break;;
	case 'c':raster_channel_order[i]+=0x80; break;;
	case 'm':raster_channel_order[i]+=0x80; break;;
	case 'k':raster_channel_order[i]+=0x80; break;;
	}
      }
    }
    stp_zfwrite((const char *)raster_channel_order,init->num_channels, 1, v);
  }
  else
    {
      stp_zfwrite((const char *)init->channel_order,init->num_channels, 1, v);
    }
}




static void
canon_init_printer(const stp_vars_t *v, const canon_privdata_t *init)
{
  unsigned int mytop;
  /* init printer */
  if (init->is_first_page) {
    canon_init_resetPrinter(v,init);       /* ESC [K */
    canon_init_setESC_M(v,init);           /* ESC (M */
    canon_init_setDuplex(v,init);          /* ESC ($ */
  }
  canon_init_setPageMode(v,init);        /* ESC (a */
  canon_init_setDataCompression(v,init); /* ESC (b */
  canon_init_setPageID(v,init);          /* ESC (q */
  canon_init_setPrintMode(v,init);       /* ESC (m */
  canon_init_setResolution(v,init);      /* ESC (d */
  canon_init_setImage(v,init);           /* ESC (t */
  canon_init_setColor(v,init);           /* ESC (c */
  canon_init_setPageMargins(v,init);     /* ESC (g */
  canon_init_setPageMargins2(v,init);    /* ESC (p */
  canon_init_setESC_P(v,init);           /* ESC (P */
  canon_init_setCartridge(v,init);       /* ESC (T */
  canon_init_setESC_S(v,init);           /* ESC (S */
  canon_init_setTray(v,init);            /* ESC (l */
  canon_init_setX72(v,init);             /* ESC (r */
  canon_init_setMultiRaster(v,init);     /* ESC (I (J (L */

  /* some linefeeds */

  mytop= (init->top*init->mode->ydpi)/72;

  if(init->caps->features & CANON_CAP_I)
    /* mytop /= init->caps->raster_lines_per_block; */
    mytop /= init->mode->raster_lines_per_block;

  if(mytop)
    canon_cmd(v,ESC28,0x65, 2, (mytop >> 8 ),(mytop & 255));
}

static void
canon_deinit_printer(const stp_vars_t *v, const canon_privdata_t *init)
{
  /* eject page */
  stp_putc(0x0c,v);

  /* say goodbye */
  canon_cmd(v,ESC28,0x62,1,0);
  if (init->caps->features & CANON_CAP_a)
    canon_cmd(v,ESC28,0x61, 1, 0);
}

static int
canon_start_job(const stp_vars_t *v, stp_image_t *image)
{
  const canon_cap_t * caps = canon_get_model_capabilities(v);
  /* output XML for iP2700 and other devices */
  if (caps->features & CANON_CAP_XML) {
    int length=strlen(prexml_iP2700); /* 680 */
    stp_zfwrite((const char*)prexml_iP2700,length,1,v);
  }
  return 1;
}

static int
canon_end_job(const stp_vars_t *v, stp_image_t *image)
{
  const canon_cap_t * caps = canon_get_model_capabilities(v);
  canon_cmd(v,ESC40,0,0);
  /* output XML for iP2700 and other devices */
  if (caps->features & CANON_CAP_XML) {
    int length=strlen(postxml_iP2700); /* 263 */
    stp_zfwrite((const char*)postxml_iP2700,length,1,v);
  }
  return 1;
}

/*
 * 'advance_buffer()' - Move (num) lines of length (len) down one line
 *                      and sets first line to 0s
 *                      accepts NULL pointers as buf
 *                  !!! buf must contain more than (num) lines !!!
 *                      also sets first line to 0s if num<1
 */
static void
canon_advance_buffer(unsigned char *buf, int len, int num)
{
  if (!buf || !len) return;
  if (num>0) memmove(buf+len,buf,len*num);
  memset(buf,0,len);
}

static void
canon_printfunc(stp_vars_t *v)
{
  int i;
  canon_privdata_t *pd = (canon_privdata_t *) stp_get_component_data(v, "Driver");
  canon_write_line(v);
  for (i = 0; i < pd->num_channels ; i++)
    canon_advance_buffer(pd->channels[i].buf, pd->length, pd->channels[i].delay);

}

static double
get_double_param(stp_vars_t *v, const char *param)
{
  if (param && stp_check_float_parameter(v, param, STP_PARAMETER_ACTIVE))
    return stp_get_float_parameter(v, param);
  else
    return 1.0;
}



static void
set_mask(unsigned char *cd_mask, int x_center, int scaled_x_where,
         int limit, int expansion, int invert)
{
  int clear_val = invert ? 255 : 0;
  int set_val = invert ? 0 : 255;
  int bytesize = 8 / expansion;
  int byteextra = bytesize - 1;
  int first_x_on = x_center - scaled_x_where;
  int first_x_off = x_center + scaled_x_where;
  if (first_x_on < 0)
    first_x_on = 0;
  if (first_x_on > limit)
    first_x_on = limit;
  if (first_x_off < 0)
    first_x_off = 0;
  if (first_x_off > limit)
    first_x_off = limit;
  first_x_on += byteextra;
  if (first_x_off > (first_x_on - byteextra))
    {
      int first_x_on_byte = first_x_on / bytesize;
      int first_x_on_mod = expansion * (byteextra - (first_x_on % bytesize));
      int first_x_on_extra = ((1 << first_x_on_mod) - 1) ^ clear_val;
      int first_x_off_byte = first_x_off / bytesize;
      int first_x_off_mod = expansion * (byteextra - (first_x_off % bytesize));
      int first_x_off_extra = ((1 << 8) - (1 << first_x_off_mod)) ^ clear_val;
      if (first_x_off_byte < first_x_on_byte)
        {
          /* This can happen, if 6 or fewer points are turned on */
          cd_mask[first_x_on_byte] = first_x_on_extra & first_x_off_extra;
        }
      else
        {
          if (first_x_on_extra != clear_val)

            cd_mask[first_x_on_byte - 1] = first_x_on_extra;
          if (first_x_off_byte > first_x_on_byte)
            memset(cd_mask + first_x_on_byte, set_val,
                   first_x_off_byte - first_x_on_byte);
          if (first_x_off_extra != clear_val)
            cd_mask[first_x_off_byte] = first_x_off_extra;
        }
    }
}


/* get delay settings for the specified color and mode */
static int canon_get_delay(canon_privdata_t* privdata,char color){
    int i=0;
    int delay = 0;
    const canon_delay_t* delaylist = privdata->mode->delay;

    while(delaylist && delaylist[i].color){
        if(delaylist[i].color == color){
           delay = delaylist[i].delay;
           break;
        }
        ++i;
    }
    if(delay > privdata->delay_max)
       privdata->delay_max = delay;
    return delay;
}


/* add a single channel to the dither engine */
static int canon_setup_channel(stp_vars_t *v,canon_privdata_t* privdata,int channel,int subchannel,const canon_inkset_t* ink,stp_shade_t** shades){
    if(ink->channel && ink->density > 0.0){
        int delay = canon_get_delay(privdata,ink->channel);
        canon_channel_t* current;
	stp_dprintf(STP_DBG_CANON, v, "canon_setup_channel: (start) privdata->num_channels %d\n", privdata->num_channels);
	stp_dprintf(STP_DBG_CANON, v, "canon_setup_channel: (start) privdata->channel_order %s\n", privdata->channel_order);
        /* create a new channel */
        privdata->channels = stp_realloc(privdata->channels,sizeof(canon_channel_t) * (privdata->num_channels + 1));
        privdata->channel_order = stp_realloc(privdata->channel_order,privdata->num_channels + 2);
        /* update channel order */
        privdata->channel_order[privdata->num_channels]=ink->channel;
	stp_dprintf(STP_DBG_CANON, v, "canon_setup_channel: ink->channel %c\n", ink->channel);
        privdata->channel_order[privdata->num_channels+1]='\0';
	stp_dprintf(STP_DBG_CANON, v, "canon_setup_channel: (terminated)privdata->channel_order %s\n", privdata->channel_order);
        current = &(privdata->channels[privdata->num_channels]);
        ++privdata->num_channels;
        /* fill ink properties */
        current->name = ink->channel;
	stp_dprintf(STP_DBG_CANON, v, "canon_setup_channel: current->name %c\n", current->name);
        current->props = ink->ink;
        current->delay = delay;
        /* calculate buffer length */
        current->buf_length = ((privdata->length * current->props->bits)+1)*(delay + 1);
        /* update maximum buffer length */
        if(current->buf_length > privdata->buf_length_max)
             privdata->buf_length_max = current->buf_length;
        /* allocate buffer for the raster data */
        current->buf = stp_zalloc(current->buf_length + 1);
        /* add channel to the dither engine */
        stp_dither_add_channel(v, current->buf , channel , subchannel);

        /* add shades to the shades array */
        *shades = stp_realloc(*shades,(subchannel + 1) * sizeof(stp_shade_t));
	/* move previous shades up one position as set_inks_full expects the subchannels first */
	if(subchannel)
		memmove(*shades + 1,*shades,sizeof(stp_shade_t) * subchannel);
        (*shades)[0].value = ink->density;
	stp_dprintf(STP_DBG_CANON, v, "canon_setup_channel: ink->density %.3f\n", ink->density);
        (*shades)[0].numsizes = ink->ink->numsizes;
	/* test for 4-4 inket with 8 levels spaced every 2nd */
	/*if (ink->ink->bits == 4)
	  (*shades)[0].numsizes = 8;*/

        (*shades)[0].dot_sizes = ink->ink->dot_sizes;
        return 1;
    } 
    return 0;
}





/* setup the dither channels */
static void canon_setup_channels(stp_vars_t *v,canon_privdata_t* privdata){
    /* (in gutenprint notation) => KCMY,  1230 => CMYK etc. */
    const char default_channel_order[STP_NCOLORS] = {0,1,2,3};
    /* codes for the primary channels */
    const char primary[STP_NCOLORS] = {'K','C','M','Y',};
    /* codes for the subchannels */
    const char secondary[STP_NCOLORS] = {'k','c','m','y'};
    /* names of the density adjustment controls */
    const char *primary_density_control[STP_NCOLORS] = {"BlackDensity","CyanDensity","MagentaDensity","YellowDensity"};
    const char *secondary_density_control[STP_NCOLORS] = {NULL,"LightCyanTrans","LightMagentaTrans","LightYellowTrans"};
    /* ink darkness for every channel */
    const double ink_darkness[] = {1.0, 0.31 / .5, 0.61 / .97, 0.08};
    const char* channel_order = default_channel_order;



    int channel;
    int channel_idx;

    if(privdata->caps->channel_order)
        channel_order = privdata->caps->channel_order;


    /* loop through the dither channels */
    for(channel_idx = 0; channel_idx < STP_NCOLORS ; channel_idx++){
        int i;
        unsigned int subchannel = 0;
        stp_shade_t* shades = NULL;
	int is_black_channel = 0;
        channel = channel_order[channel_idx];
	stp_dprintf(STP_DBG_CANON, v, "canon_setup_channels: channel %d\n", channel);
        if(channel == STP_ECOLOR_K && privdata->used_inks & CANON_INK_K_MASK){ /* black channel */
            /* find K and k inks */
            for(i=0;i<privdata->mode->num_inks;i++){
                const canon_inkset_t* ink = &privdata->mode->inks[i];
                if(ink->channel == primary[channel] || ink->channel == secondary[channel]) {
                    subchannel += canon_setup_channel(v,privdata,channel,subchannel,ink,&shades);
		    /* Gernot: add */
		    stp_dprintf(STP_DBG_CANON, v, "canon_setup_channels: got a black channel\n");
		}
            }
	    is_black_channel = 1;
	    /* adding cmy channels */
	    /*}else if(channel != STP_ECOLOR_K && privdata->used_inks & (CANON_INK_CMY_MASK | CANON_INK_cmy_MASK)){ */ /* color channels */
        }else if(channel != STP_ECOLOR_K && privdata->used_inks & CANON_INK_CMY_MASK){  /* color channels */
            for(i=0;i<privdata->mode->num_inks;i++){
                const canon_inkset_t* ink = &privdata->mode->inks[i];
		stp_dprintf(STP_DBG_CANON, v, "canon_setup_channels: loop non-K inks %d\n", i);
                /*if(ink->channel == primary[channel] || ((privdata->used_inks & (CANON_INK_CcMmYyKk_MASK | CANON_INK_cmy_MASK)) && (ink->channel == secondary[channel]))) {*/
                if(ink->channel == primary[channel] || ((privdata->used_inks & (CANON_INK_CcMmYyKk_MASK|CANON_INK_CMY_MASK)) && (ink->channel == secondary[channel]))) {
		/* Gernot: see if this works: use the masks that includes secondary channels */
                /* if(ink->channel == primary[channel] || ((privdata->used_inks & CANON_INK_CMYKk_MASK ) && (ink->channel == secondary[channel]))) {*/
		  subchannel += canon_setup_channel(v,privdata,channel,subchannel,ink,&shades);
		  stp_dprintf(STP_DBG_CANON, v, "canon_setup_channels: adding subchannel\n");
		}
		else {
		  stp_dprintf(STP_DBG_CANON, v, "canon_setup_channels: not creating subchannel\n"); 
		}
            } 
        }

        /* set inks and density */
        if(shades){
          stp_dither_set_inks_full(v,channel, subchannel, shades, 1.0, ink_darkness[channel]);
          for(i=0;i<subchannel;i++){
            double density = get_double_param(v, primary_density_control[channel]) * get_double_param(v, "Density");
	    stp_dprintf(STP_DBG_CANON, v, "canon_setup_channels: loop subchannels for shades %d\n", i);
            if(i > 0 && secondary_density_control[channel])
              density *= get_double_param(v, secondary_density_control[channel]);
            stp_channel_set_density_adjustment(v,channel,subchannel,density);
          }
	  if (is_black_channel)
	    stp_channel_set_black_channel(v, channel);
          stp_free(shades);
        }
    }
}







/* FIXME move this to printercaps */
#define CANON_CD_X 176
#define CANON_CD_Y 405

static void setup_page(stp_vars_t* v,canon_privdata_t* privdata){
  const char    *media_source = stp_get_string_parameter(v, "InputSlot");
  const char *cd_type = stp_get_string_parameter(v, "PageSize");
  int print_cd= (media_source && (!strcmp(media_source, "CD")));
  int           page_left,
                page_top,
                page_right,
                page_bottom;
  int hub_size = 0;

 
  if (cd_type && (strcmp(cd_type, "CDCustom") == 0 ))
     {
	int outer_diameter = stp_get_dimension_parameter(v, "CDOuterDiameter");
	stp_set_page_width(v, outer_diameter);
	stp_set_page_height(v, outer_diameter);
	stp_set_width(v, outer_diameter);
	stp_set_height(v, outer_diameter);
	hub_size = stp_get_dimension_parameter(v, "CDInnerDiameter");
     }
 else
    {
	const char *inner_radius_name = stp_get_string_parameter(v, "CDInnerRadius");
  	hub_size = 43 * 10 * 72 / 254;		/* 43 mm standard CD hub */

  	if (inner_radius_name && strcmp(inner_radius_name, "Small") == 0)
   	  hub_size = 16 * 10 * 72 / 254;		/* 15 mm prints to the hole - play it
				   safe and print 16 mm */
    }

  privdata->top = stp_get_top(v);
  privdata->left = stp_get_left(v);
  privdata->out_width = stp_get_width(v); /* check Epson: page_true_width */
  privdata->out_height = stp_get_height(v); /* check Epson: page_true_height */

  stp_deprintf(STP_DBG_CANON,"stp_get_width: privdata->out_width is %i\n",privdata->out_width);
  stp_deprintf(STP_DBG_CANON,"stp_get_height: privdata->out_height is %i\n",privdata->out_height);

  /* Don't use full bleed mode if the paper itself has a margin */
  if (privdata->left > 0 || privdata->top > 0)
    stp_set_boolean_parameter(v, "FullBleed", 0);

  internal_imageable_area(v, 0, 0, &page_left, &page_right,
                          &page_bottom, &page_top);
  if (print_cd) {
    privdata->cd_inner_radius = hub_size / 2;
    privdata->cd_outer_radius = stp_get_width(v) / 2;
    privdata->left = CANON_CD_X - privdata->cd_outer_radius + stp_get_dimension_parameter(v, "CDXAdjustment");;
    privdata->top = CANON_CD_Y - privdata->cd_outer_radius + stp_get_dimension_parameter(v, "CDYAdjustment");
    privdata->page_width = privdata->left + privdata->out_width;
    privdata->page_height = privdata->top + privdata->out_height;
  } else {
    privdata->left -= page_left;
    privdata->top -= page_top; /* checked in Epson: matches */
    privdata->page_width = page_right - page_left; /* checked in Epson: matches */
    privdata->page_height = page_bottom - page_top; /* checked in Epson: matches */

    if (ERRPRINT) {
      stp_eprintf(v,"============================set_imageable_area========================\n");
      stp_eprintf(v,"setup_page page_top = %i\n",page_top);
      stp_eprintf(v,"setup_page page_bottom = %i\n",page_bottom);
      stp_eprintf(v,"setup_page page_left = %i\n",page_left);
      stp_eprintf(v,"setup_page page_right = %i\n",page_right);
      stp_eprintf(v,"setup_page top = %i\n",privdata->top);
      stp_eprintf(v,"setup_page left = %i\n",privdata->left);
      stp_eprintf(v,"setup_page out_height = %i\n",privdata->out_height);
      stp_eprintf(v,"setup_page page_height = %i\n",privdata->page_height);
      stp_eprintf(v,"setup_page page_width = %i\n",privdata->page_width);
    }

    stp_dprintf(STP_DBG_CANON, v, "setup_page page_top = %i\n",page_top);
    stp_dprintf(STP_DBG_CANON, v, "setup_page page_bottom = %i\n",page_bottom);
    stp_dprintf(STP_DBG_CANON, v, "setup_page page_left = %i\n",page_left);
    stp_dprintf(STP_DBG_CANON, v, "setup_page page_right = %i\n",page_right);
    stp_dprintf(STP_DBG_CANON, v, "setup_page top = %i\n",privdata->top);
    stp_dprintf(STP_DBG_CANON, v, "setup_page left = %i\n",privdata->left);
    stp_dprintf(STP_DBG_CANON, v, "setup_page out_height = %i\n",privdata->out_height);
    stp_dprintf(STP_DBG_CANON, v, "setup_page page_height = %i\n",privdata->page_height);
    stp_dprintf(STP_DBG_CANON, v, "setup_page page_width = %i\n",privdata->page_width);

  }
}


/* combine all curve parameters in s and apply them */
static void canon_set_curve_parameter(stp_vars_t *v,const char* type,stp_curve_compose_t comp,const char* s1,const char* s2,const char* s3){
  const char * s[3];
  size_t count = sizeof(s) / sizeof(s[0]); 
  stp_curve_t *ret = NULL;
  int curve_count = 0;
  int i;
  const size_t piecewise_point_count = 384;


  /* ignore settings from the printercaps if the user specified his own parameters */
  if(stp_check_curve_parameter(v,type, STP_PARAMETER_ACTIVE))
    return;

  /* init parameter list (FIXME pass array directly???)*/
  s[0] = s1;
  s[1] = s2;
  s[2] = s3;

  /* skip empty curves */
  for(i=0;i<count;i++){
    if(s[i])
      s[curve_count++] = s[i];
  }

  /* combine curves */
  if(curve_count){
    for(i=0;i<curve_count;i++){
      stp_curve_t* t_tmp = stp_curve_create_from_string(s[i]);
      if(t_tmp){
        if(stp_curve_is_piecewise(t_tmp)){
          stp_curve_resample(t_tmp, piecewise_point_count);
        }
        if(!ret){
          ret = t_tmp;
        }else{
          stp_curve_t* t_comp = NULL;
          stp_curve_compose(&t_comp, ret, t_tmp, comp, -1);
          if(t_comp){
            stp_curve_destroy(ret);
            ret = t_comp;
          }
          stp_curve_destroy(t_tmp);
        }
      }
    }
  }

  /* apply result */
  if(ret){
    stp_set_curve_parameter(v, type, ret);
    stp_curve_destroy(ret);
  }
}

/*
 * 'canon_print()' - Print an image to a CANON printer.
 */
static int
canon_do_print(stp_vars_t *v, stp_image_t *image)
{
  int i;
  int		status = 1;
  const char	*media_source = stp_get_string_parameter(v, "InputSlot");
  const char    *ink_type = stp_get_string_parameter(v, "InkType");
  const char    *duplex_mode =stp_get_string_parameter(v, "Duplex");
  int           page_number = stp_get_int_parameter(v, "PageNumber");
  const canon_cap_t * caps= canon_get_model_capabilities(v);
  const canon_modeuselist_t* mlist = caps->modeuselist;
#if 0
  const canon_modeuse_t* muse;
#endif
  /*  int monocheck = 0;
      int colcheck = 0; */
  int		x,y;		/* Looping vars */
  canon_privdata_t privdata;
  int		errdiv,		/* Error dividend */
		errmod,		/* Error modulus */
		errval,		/* Current error value */
		errline,	/* Current raster line */
                errlast;	/* Last raster line loaded */
#if 0
		out_channels;	/* Output bytes per pixel */
#endif
  unsigned	zero_mask;
  int           print_cd= (media_source && (!strcmp(media_source, "CD")));
  int           image_height;
#if 0
  int           image_width;
#endif
  double        k_upper, k_lower;
  unsigned char *cd_mask = NULL;
  double outer_r_sq = 0;
  double inner_r_sq = 0;
  unsigned char* weave_cols[4] ; /* TODO clean up weaving code to be more generic */

  stp_dprintf(STP_DBG_CANON, v, "Entering canon_do_print\n");

  if (!stp_verify(v))
    {
      stp_eprintf(v, "Print options not verified; cannot print.\n");
      return 0;
    }
  /*
  * Setup a read-only pixel region for the entire image...
  */

  stp_image_init(image);


  /* rotate even pages for DuplexNoTumble */
  if((page_number & 1) && duplex_mode && !strcmp(duplex_mode,"DuplexNoTumble"))
  	image = stpi_buffer_image(image,BUFFER_FLAG_FLIP_X | BUFFER_FLAG_FLIP_Y);

  memset(&privdata,0,sizeof(canon_privdata_t));
  privdata.caps = caps;

  /* find the wanted media type */
  /* - media type has priority
     - then we select source
     - then inkset (cartridge selection)
     - then we select duplex
     - after that we compare if mode is compatible with media
     - if not, we replace it using closest quality setting
     - then we decide on printhead colors based on actual mode to use
   */

  privdata.pt = get_media_type(caps,stp_get_string_parameter(v, "MediaType"));
  privdata.slot = canon_source_type(media_source,caps);

  /* ---  make adjustment to InkSet based on Media --- */

  /* cartridge selection if any: default is Both---but should change to NULL if CANON_CAP_T is not available */
  /* check if InkSet chosen is possible for this Media */
  /* - if Black, check if modes for selected media have a black flag */
  /*   else, set InkSet to "Both" for now */

  /* scroll through modeuse list to find media */
  for(i=0;i<mlist->count;i++){
    if(!strcmp(privdata.pt->name,mlist->modeuses[i].name)){
#if 0
      muse = &mlist->modeuses[i];
#endif
      break;
    }
  }

  if ( !strcmp(stp_get_string_parameter(v, "InkSet"),"Black")) {
    /* check if there is any mode for that media with K-only inktype */
    /* if not, change it to "Both" */
    /* NOTE: User cannot force monochrome printing here, since that would require changing the Color Model */
    if (!(mlist->modeuses[i].use_flags & INKSET_BLACK_SUPPORT)) {
      stp_set_string_parameter(v, "InkSet", "Both");	
    }
  }
  /* Color-only */
  else if ( !strcmp(stp_get_string_parameter(v, "InkSet"),"Color") && (caps->features & CANON_CAP_T) ) {
    /* check if there is any mode for that media with no K in the inkset at all */
    /* if not, change it to "Both" */
    if (!(mlist->modeuses[i].use_flags & INKSET_COLOR_SUPPORT)) {
      stp_set_string_parameter(v, "InkSet", "Both");	
    }
  }
  /* no restriction for "Both" (non-BJC) or "Color" (BJC) or "Photo" yet */

  /* get InkSet after adjustment */
  privdata.ink_set = stp_get_string_parameter(v, "InkSet");

  /* --- no current restrictions for Duplex setting --- */

  /* in particular, we do not constraint duplex printing to certain media */
  privdata.duplex_str = duplex_mode;

  /* ---  make adjustment to InkType to comply with InkSet --- */

  /*  although InSet adjustment is pre-supposed, even if InkSet is not
      adjusted, the InkType adjustment will be validated against mode
      later */
  if (!strcmp(privdata.ink_set,"Black")) {
    if (strcmp(ink_type,"Gray")) {/* if ink_type is NOT set to Gray yet */
      stp_dprintf(STP_DBG_CANON, v, "canon_do_print: InkSet Black, so InkType set to Gray\n");
      stp_set_string_parameter(v, "InkType", "Gray");
    }
  } /* Color-only */
  else if ( !strcmp(privdata.ink_set,"Color") && (caps->features & CANON_CAP_T) ) {
    if (strcmp(ink_type,"RGB")) {/* if ink_type is NOT set to RGB (CMY) yet */
      stp_dprintf(STP_DBG_CANON, v, "canon_do_print: InkSet Color, so InkType changed to RGB (CMY)\n");
      stp_set_string_parameter(v, "InkType", "RGB");
    }
  } /* no restriction for InkSet set to "Both" or "Photo" */

  /* --- make adjustments to mode --- */

  /* find the wanted print mode: NULL if not yet set */
  if (ERRPRINT)
    stp_eprintf(v,"Calling get_current_parameter from canon_do_print routine (before default set)");
  stp_dprintf(STP_DBG_CANON, v, "canon_do_print: calling canon_get_current_mode\n");
  privdata.mode = canon_get_current_mode(v);

  if(!privdata.mode) {
    privdata.mode = &caps->modelist->modes[caps->modelist->default_mode];
  }
  
  /* then call get_current_mode again to sort out the correct matching of parameters and mode selection */
  if (ERRPRINT)
    stp_eprintf(v,"Calling cannon_check_current_parameter from canon_do_print routine (after default set)");
  
  stp_dprintf(STP_DBG_CANON, v, "canon_do_print: calling canon_check_current_mode\n");

  privdata.mode = canon_check_current_mode(v);

  /* --- completed all adjustments: options should be consistent --- */

  /* set quality */
  privdata.quality = privdata.mode->quality;


  /* force grayscale if image is grayscale
   *                 or single black cartridge installed
   */
  privdata.used_inks = canon_printhead_colors(v);
  if (privdata.used_inks == CANON_INK_K)
      stp_set_string_parameter(v, "PrintingMode", "BW");
  else
    stp_set_string_parameter(v, "PrintingMode", "Color");

  setup_page(v,&privdata);

  image_height = stp_image_height(image);

#if 0
  image_width = stp_image_width(image);
#endif

  privdata.is_first_page = (page_number == 0);

 /*
  * Convert image size to printer resolution...
  */
#if 0
  stp_deprintf(STP_DBG_CANON,"canon_do_print: unused image_width is %i pts(?)\n",image_width);
#endif
  stp_deprintf(STP_DBG_CANON,"canon_do_print: privdata.out_width is %i pts\n",privdata.out_width);
  stp_deprintf(STP_DBG_CANON,"canon_do_print: privdata.out_height is %i pts\n",privdata.out_height);
  stp_deprintf(STP_DBG_CANON,"canon_do_print: privdata.left is %i pts\n",privdata.left);

  privdata.out_width  = privdata.mode->xdpi * privdata.out_width / 72;
  privdata.out_height = privdata.mode->ydpi * privdata.out_height / 72;
  privdata.left       = privdata.mode->xdpi * privdata.left / 72;

  stp_deprintf(STP_DBG_CANON,"canon_do_print: privdata.out_width is %i dots\n",privdata.out_width);
  stp_deprintf(STP_DBG_CANON,"canon_do_print: privdata.out_height is %i dots\n",privdata.out_height);
  stp_deprintf(STP_DBG_CANON,"canon_do_print: privdata.left is %i dots\n",privdata.left);

  stp_deprintf(STP_DBG_CANON,"density is %f\n",
               stp_get_float_parameter(v, "Density"));

  /*
   * Compute the LUT.  For now, it's 8 bit, but that may eventually
   * sometimes change.
   */

  if (!stp_check_float_parameter(v, "Density", STP_PARAMETER_DEFAULTED))
    {
      stp_set_float_parameter_active(v, "Density", STP_PARAMETER_ACTIVE);
      stp_set_float_parameter(v, "Density", 1.0);
    }

  stp_scale_float_parameter(v, "Density", privdata.pt->base_density);
  stp_scale_float_parameter(v, "Density",privdata.mode->density);

  if (stp_get_float_parameter(v, "Density") > 1.0)
    stp_set_float_parameter(v, "Density", 1.0);

  if (privdata.used_inks == CANON_INK_K)
    stp_scale_float_parameter(v, "Gamma", 1.25);
  stp_scale_float_parameter( v, "Gamma", privdata.mode->gamma );

  stp_deprintf(STP_DBG_CANON,"density is %f\n",
               stp_get_float_parameter(v, "Density"));

  if(privdata.used_inks & CANON_INK_CMYK_MASK)
    stp_set_string_parameter(v, "STPIOutputType", "KCMY");
  else if(privdata.used_inks & CANON_INK_CMY_MASK)
    stp_set_string_parameter(v, "STPIOutputType", "CMY");
  /* Gernot: addition */
  /*else if(privdata.used_inks & CANON_INK_cmy_MASK)
    stp_set_string_parameter(v, "STPIOutputType", "cmy");*/
  else
    stp_set_string_parameter(v, "STPIOutputType", "Grayscale");

  privdata.length = (privdata.out_width + 7) / 8;

  stp_deprintf(STP_DBG_CANON,"privdata.length is %i\n",privdata.length);
  stp_deprintf(STP_DBG_CANON,"canon_do_print: privdata.num_channels is %i\n",privdata.num_channels);

  stp_dither_init(v, image, privdata.out_width, privdata.mode->xdpi, privdata.mode->ydpi);


  stp_deprintf(STP_DBG_CANON,"privdata.out_width is %i (after stp_dither_init)\n",privdata.out_width);
  stp_deprintf(STP_DBG_CANON,"privdata.length is %i (after stp_dither_init)\n",privdata.length);
  stp_deprintf(STP_DBG_CANON,"canon_do_print: privdata.num_channels is %i (after stp_dither_init)\n",privdata.num_channels);

  canon_setup_channels(v,&privdata);

  stp_deprintf(STP_DBG_CANON,"privdata.out_width is %i (after canon_setup_channels)\n",privdata.out_width);
  stp_deprintf(STP_DBG_CANON,"privdata.length is %i (after canon_setup_channels)\n",privdata.length);
  stp_deprintf(STP_DBG_CANON,"canon_do_print: privdata.num_channels is %i (after canon_setup_channels)\n",privdata.num_channels);

  stp_deprintf(STP_DBG_CANON,
	       "canon: driver will use colors %s\n",privdata.channel_order);

  /* Allocate compression buffer */
  if(caps->features & CANON_CAP_I)
    /*privdata.comp_buf = stp_zalloc(privdata.buf_length_max * 2 * caps->raster_lines_per_block * privdata.num_channels); */
      privdata.comp_buf = stp_zalloc(privdata.buf_length_max * 2 * privdata.mode->raster_lines_per_block * privdata.num_channels); /* for multiraster we need to buffer 8 lines for every color */
  else
      privdata.comp_buf = stp_zalloc(privdata.buf_length_max * 2);
  /* Allocate fold buffer */
  privdata.fold_buf = stp_zalloc(privdata.buf_length_max);



 /*
  * Output the page...
  */

   /* FIXME this is probably broken, kept for backward compatibility */
   if(privdata.num_channels > 4){
       k_lower = 0.4 / privdata.channels[4].props->bits + .1;
   }else 
       k_lower = 0.25;

  k_lower *= privdata.pt->k_lower_scale;
  k_upper = privdata.pt->k_upper;

  if (!stp_check_float_parameter(v, "GCRLower", STP_PARAMETER_ACTIVE))
    stp_set_default_float_parameter(v, "GCRLower", k_lower);
  if (!stp_check_float_parameter(v, "GCRUpper", STP_PARAMETER_ACTIVE))
    stp_set_default_float_parameter(v, "GCRUpper", k_upper);


  /* init the printer */
  canon_init_printer(v, &privdata);

  /* initialize weaving for S200 for resolutions > 360dpi */
  if (privdata.mode->flags & MODE_FLAG_WEAVE)
     {
       char weave_color_order[] = "KCMY";

       privdata.stepper_ydpi = 720;
       privdata.nozzle_ydpi = 360;
       if (privdata.mode->xdpi == 2880)
         privdata.physical_xdpi = 2880;
       else
         privdata.physical_xdpi = 720;

       stp_deprintf(STP_DBG_CANON,"canon: adjust leftskip: old=%d,\n", privdata.left);
       privdata.left = (int)( (float)privdata.left * (float)privdata.physical_xdpi / (float)privdata.mode->xdpi ); /* adjust left margin */
       stp_deprintf(STP_DBG_CANON,"canon: adjust leftskip: new=%d,\n", privdata.left);

       privdata.ncolors = 4;
       privdata.head_offset = stp_zalloc(sizeof(int) * privdata.ncolors);
       memset(privdata.head_offset, 0, sizeof(*privdata.head_offset));

       if ( privdata.used_inks == CANON_INK_K )
           privdata.nozzles = 64; /* black nozzles */
       else
           privdata.nozzles = 24; /* color nozzles */
       if ( privdata.used_inks == CANON_INK_K )
         {
           privdata.ncolors = 1;
           privdata.head_offset[0] = 0; /* K starts at 0 */
           privdata.head_offset[1] = 0 ;/* how far C starts after K */
           privdata.head_offset[2] = 0;/* how far M starts after K */
           privdata.head_offset[3] = 0;/* how far Y starts after K */
           privdata.top += 11;
         }
       else if ( privdata.used_inks == CANON_INK_CMYK )
         {
           privdata.head_offset[0] = 0; /* K starts at 0 */
           privdata.head_offset[1] = 144 ;/* how far C starts after K */
           privdata.head_offset[2] = 144 + 64;/* how far M starts after K */
           privdata.head_offset[3] = 144 + 64 + 64;/* how far Y starts after K */
           privdata.top += 5;
         }
       else  /* colormode == CMY */
         {
           privdata.ncolors = 3;
           privdata.head_offset[0] = 0; /* K starts at 0 */
           privdata.head_offset[1] = 0 ;/* how far C starts after K */
           privdata.head_offset[2] = 64;/* how far M starts after K */
           privdata.head_offset[3] = 128;/* how far Y starts after K */
           privdata.top += 18;
         }

       privdata.nozzle_separation = privdata.stepper_ydpi / privdata.nozzle_ydpi;
       privdata.horizontal_passes = privdata.mode->xdpi / privdata.physical_xdpi;
       privdata.vertical_passes = 1;
       privdata.vertical_oversample = privdata.mode->ydpi / privdata.stepper_ydpi;
       privdata.bidirectional = 1; /* 1: bidirectional; 0: unidirectional  printing */
       privdata.direction = 1;
       stp_allocate_component_data(v, "Driver", NULL, NULL, &privdata);
       stp_deprintf(STP_DBG_CANON,"canon: initializing weaving: nozzles=%d, nozzle_separation=%d,\n"
                                    "horizontal_passes=%d, vertical_passes=%d,vertical_oversample=%d,\n"
                                    "ncolors=%d, out_width=%d, out_height=%d\n"
                                    "weave_top=%d, weave_page_height=%d \n"
                                    "head_offset=[%d,%d,%d,%d]  \n",
                                    privdata.nozzles, privdata.nozzle_separation,
                                    privdata.horizontal_passes, privdata.vertical_passes,
                                    privdata.vertical_oversample, privdata.ncolors,
                                    privdata.out_width, privdata.out_height,
                                    privdata.top * privdata.stepper_ydpi / 72, privdata.page_height * privdata.stepper_ydpi / 72,
                                    privdata.head_offset[0],privdata.head_offset[1],
                                    privdata.head_offset[2],privdata.head_offset[3]);

       stp_initialize_weave(v, privdata.nozzles, privdata.nozzle_separation,
                                privdata.horizontal_passes, privdata.vertical_passes,
                                privdata.vertical_oversample, privdata.ncolors,
                                1,
                                privdata.out_width, privdata.out_height,
                                privdata.top * privdata.stepper_ydpi / 72,
                                privdata.page_height * privdata.stepper_ydpi / 72,
                                privdata.head_offset,
                                STP_WEAVE_ZIGZAG,
                                canon_flush_pass,
                                stp_fill_uncompressed,
                                stp_pack_uncompressed,
                                stp_compute_uncompressed_linewidth);
       privdata.last_pass_offset = 0;

       if (ERRPRINT) {
	 for(x=0;x<4;x++){
	   stp_eprintf(v, "DEBUG print-canon weave: weave_color_order[%d]: %u\n",
		       x, (unsigned int)weave_color_order[x]);
	 }
	 for(x=0;x<privdata.num_channels;x++){
	   stp_eprintf(v, "DEBUG print-canon weave: channel_order[%d]: %u\n",
		       x, (unsigned int)privdata.channel_order[x]);
	 }
       }

       for(i=0;i<4;i++){/* need all 4 channels for weave_cols, but not for privdata.num_channels! */
	   /* see if it helps to initialize to zero */
	   weave_cols[i] = 0;
	   privdata.weave_bits[i] = 0;

           for(x=0;x<privdata.num_channels;x++){
	     if(weave_color_order[i] == privdata.channel_order[x]){
	       weave_cols[i] = privdata.channels[x].buf;
	       privdata.weave_bits[i] = privdata.channels[x].props->bits;
	       if (ERRPRINT)
		 stp_eprintf(v, "DEBUG print-canon weave: set weave_cols[%d] to privdata.channels[%d].buf\n",
			     i, x);
	     }
           }
       }
  }


  errdiv  = image_height / privdata.out_height;
  errmod  = image_height % privdata.out_height;
  errval  = 0;
  errlast = -1;
  errline  = 0;

  /* set Hue, Lum and Sat Maps */ 
  canon_set_curve_parameter(v,"HueMap",STP_CURVE_COMPOSE_ADD,caps->hue_adjustment,privdata.pt->hue_adjustment,privdata.mode->hue_adjustment);
  canon_set_curve_parameter(v,"LumMap",STP_CURVE_COMPOSE_MULTIPLY,caps->lum_adjustment,privdata.pt->lum_adjustment,privdata.mode->lum_adjustment);
  canon_set_curve_parameter(v,"SatMap",STP_CURVE_COMPOSE_MULTIPLY,caps->sat_adjustment,privdata.pt->sat_adjustment,privdata.mode->sat_adjustment);

#if 0
  out_channels = stp_color_init(v, image, 65536);
#endif
  (void) stp_color_init(v, image, 65536);
  stp_allocate_component_data(v, "Driver", NULL, NULL, &privdata);

  privdata.emptylines = 0;
  if (print_cd) {
    cd_mask = stp_malloc(1 + (privdata.out_width + 7) / 8);
    outer_r_sq = (double)privdata.cd_outer_radius * (double)privdata.cd_outer_radius;
    inner_r_sq = (double)privdata.cd_inner_radius * (double)privdata.cd_inner_radius;
  }
  for (y = 0; y < privdata.out_height; y ++)
  {
    int duplicate_line = 1;

    if (errline != errlast)
    {
      errlast = errline;
      duplicate_line = 0;
      if (stp_color_get_row(v, image, errline, &zero_mask))
	{
	  status = 2;
	  break;
	}
    }
    if (print_cd) 
      {
	int x_center = privdata.cd_outer_radius * privdata.mode->xdpi / 72;
	int y_distance_from_center =
	  privdata.cd_outer_radius - (y * 72 / privdata.mode->ydpi);
	if (y_distance_from_center < 0)
	  y_distance_from_center = -y_distance_from_center;
	memset(cd_mask, 0, (privdata.out_width + 7) / 8);
	if (y_distance_from_center < privdata.cd_outer_radius)
	  {
	    double y_sq = (double) y_distance_from_center *
	      (double) y_distance_from_center;
	    int x_where = sqrt(outer_r_sq - y_sq) + .5;
	    int scaled_x_where = x_where * privdata.mode->xdpi / 72;
	    set_mask(cd_mask, x_center, scaled_x_where,
		     privdata.out_width, 1, 0);
	    if (y_distance_from_center < privdata.cd_inner_radius)
	      {
		x_where = sqrt(inner_r_sq - y_sq) + .5;
		scaled_x_where = x_where * privdata.mode->ydpi / 72;
		set_mask(cd_mask, x_center, scaled_x_where,
			 privdata.out_width, 1, 1);
	      }
	  }
      }
    stp_dither(v, y, duplicate_line, zero_mask, cd_mask);
    if ( privdata.mode->flags & MODE_FLAG_WEAVE )
        stp_write_weave(v, weave_cols);
    else if ( caps->features & CANON_CAP_I)
        canon_write_multiraster(v,&privdata,y);
    else
        canon_printfunc(v);
    errval += errmod;
    errline += errdiv;
    if (errval >= privdata.out_height)
    {
      errval -= privdata.out_height;
      errline ++;
    }
  }

  if ( privdata.mode->flags & MODE_FLAG_WEAVE )
  {
      stp_flush_all(v);
      canon_advance_paper(v, 5);
  }
  else
  {

  /*
   * Flush delayed buffers...
   */

  if (privdata.delay_max) {
    stp_deprintf(STP_DBG_CANON,"\ncanon: flushing %d possibly delayed buffers\n",
		 privdata.delay_max);
    for (y= 0; y<privdata.delay_max; y++) {

      canon_write_line(v);
      for (i = 0; i < privdata.num_channels; i++)
	canon_advance_buffer(privdata.channels[i].buf, privdata.length,
			     privdata.channels[i].delay);
    }
  }
  }
  stp_image_conclude(image);

 /*
  * Cleanup...
  */

  stp_free(privdata.fold_buf);
  stp_free(privdata.comp_buf);

  if(cd_mask)
      stp_free(cd_mask);


  canon_deinit_printer(v, &privdata);
  /* canon_end_job does not get called for jobmode automatically */
  if(!stp_get_string_parameter(v, "JobMode") ||
    strcmp(stp_get_string_parameter(v, "JobMode"), "Page") == 0){
    canon_end_job(v,image);
  }

  for(i=0;i< privdata.num_channels;i++)
      if(privdata.channels[i].buf)
          stp_free(privdata.channels[i].buf);
  if(privdata.channels)
      stp_free(privdata.channels);

  stp_free(privdata.channel_order);
  if (privdata.head_offset)
    stp_free(privdata.head_offset);


  return status;
}

static int
canon_print(const stp_vars_t *v, stp_image_t *image)
{
  int status;
  stp_vars_t *nv = stp_vars_create_copy(v);
  stp_prune_inactive_options(nv);
  status = canon_do_print(nv, image);
  stp_vars_destroy(nv);
  return status;
}

static const stp_printfuncs_t print_canon_printfuncs =
{
  canon_list_parameters,
  canon_parameters,
  stp_default_media_size,
  canon_imageable_area,
  canon_maximum_imageable_area,
  canon_limit,
  canon_print,
  canon_describe_resolution,
  canon_describe_output,
  stp_verify_printer_params,
  canon_start_job,
  canon_end_job,
  NULL
};

static void
canon_shift_buffer(unsigned char *line,int length,int bits)
{
  int i,j;
  for (j=0; j<bits; j++) {
    for (i=length-1; i>0; i--) {
      line[i]= (line[i] >> 1) | (line[i-1] << 7);
    }
    line[0] = line[0] >> 1;
  }
}


/* fold, apply 5 pixel in 1 byte compression, pack tiff and return the compressed length */
static int canon_compress(stp_vars_t *v, canon_privdata_t *pd, unsigned char* line,int length,int offset,unsigned char* comp_buf,int bits, int ink_flags)
{
  unsigned char
    *in_ptr= line,
    *comp_ptr, *comp_data;
  int offset2,bitoffset;

  /* Don't send blank lines... */
  
  if (line[0] == 0 && memcmp(line, line + 1, (length * bits)  - 1) == 0)
    return 0;
  
  /* if no modulation: 1 bit per pixel */
  
  offset2 = offset / 8;
  bitoffset = offset % 8;
  
  /* fold lsb/msb pairs if drop modulation is active */
  
  if (bits==2) {
    int pixels_per_byte = 4;
    if(ink_flags & INK_FLAG_5pixel_in_1byte)
      pixels_per_byte = 5;
    
    stp_fold(line,length,pd->fold_buf);
    in_ptr= pd->fold_buf;
    length= (length*8/4); /* 4 pixels in 8bit */
    /* calculate the number of compressed bytes that can be sent directly */
    offset2 = offset / pixels_per_byte;
    /* calculate the number of (uncompressed) bits that have to be added to the raster data */
    bitoffset = (offset % pixels_per_byte) * 2;
  }
  else if (bits==3) {
    stp_fold_3bit_323(line,length,pd->fold_buf);
    in_ptr= pd->fold_buf;
    length= (length*8)/3;
    offset2 = offset/3;
#if 0
    switch(offset%3){
    case 0: offset= (offset/3)*8;   break;
    case 1: offset= (offset/3)*8/*+3 CAREFUL! CANNOT SHIFT _AFTER_ RECODING!!*/; break;
    case 2: offset= (offset/3)*8/*+5 CAREFUL! CANNOT SHIFT _AFTER_ RECODING!!*/; break;
    }
#endif
    bitoffset= 0;
  }
  else if (bits==4) {
    stp_fold_4bit(line,length,pd->fold_buf);
    in_ptr= pd->fold_buf;
    length= (length*8)/2;
    offset2 = offset / 2; 
    bitoffset= offset % 2;
  }
  else if (bits==8) {
    stp_fold_8bit(line,length,pd->fold_buf);
    in_ptr= pd->fold_buf;
    length    = length*8; /* 1 pixel per 8 bits */
    offset2   = offset;
    bitoffset = 0;
  }
    
  /* pack left border rounded to multiples of 8 dots */

  comp_data= comp_buf;

  while (offset2>0) {
    unsigned char toffset = offset2 > 127 ? 127 : offset2;
    comp_data[0] = 1 - toffset;
    comp_data[1] = 0;
    comp_data += 2;
    offset2-= toffset;
  }
  if (bitoffset) {
    if (bitoffset<8)
      {
	in_ptr[ length++ ] = 0;
	canon_shift_buffer(in_ptr,length,bitoffset);
      }
    else if (bitoffset == 8)
      {
	memmove(in_ptr + 1,in_ptr,length++);
	in_ptr[0] = 0;
      }
    else
      stp_deprintf(STP_DBG_CANON,"SEVERE BUG IN print-canon.c::canon_write() "
		   "bitoffset=%d!!\n",bitoffset);
  }
  
  if(ink_flags & INK_FLAG_5pixel_in_1byte)
    length = pack_pixels(in_ptr,length);
  
  stp_pack_tiff(v, in_ptr, length, comp_data, &comp_ptr, NULL, NULL);
  
  return comp_ptr - comp_buf;
}

/*
 * 'canon_write()' - Send graphics using TIFF packbits compression.
 */

static int
canon_write(stp_vars_t *v,		/* I - Print file or command */
            canon_privdata_t *pd,       /* privdata */
	    const canon_cap_t *   caps,	        /* I - Printer model */
	    unsigned char *line,	/* I - Output bitmap data */
	    int           length,	/* I - Length of bitmap data */
	    int           coloridx,	/* I - Which color */
	    int           *empty,       /* IO- Preceeding empty lines */
	    int           width,	/* I - Printed width */
	    int           offset, 	/* I - Offset from left side */
	    int           bits,
            int           ink_flags)
{

  unsigned char color;
  int newlength = canon_compress(v,pd,line,length,offset,pd->comp_buf,bits,ink_flags);
  if(!newlength)
      return 0;
  /* send packed empty lines if any */

  if (*empty) {
    stp_zfwrite("\033\050\145\002\000", 5, 1, v);
    stp_put16_be(*empty, v);
    *empty= 0;
  }

 /* Send a line of raster graphics... */

  stp_zfwrite("\033\050\101", 3, 1, v);
  stp_put16_le(newlength + 1, v);
  color= "CMYKcmyk"[coloridx];
  if (!color) color= 'K';
  stp_putc(color,v);
  stp_zfwrite((const char *)pd->comp_buf, newlength, 1, v);
  stp_putc('\015', v);
  return 1;
}


static void
canon_write_line(stp_vars_t *v)
{
  canon_privdata_t *pd =
    (canon_privdata_t *) stp_get_component_data(v, "Driver");
  char write_sequence[] = "KYMCymck";
  static const int write_number[] = { 3, 2, 1, 0, 6, 5, 4, 7 };   /* KYMCymc */
  int i;
  int written= 0;
  for (i = 0; i < strlen(write_sequence) ; i++)
    {
      int x;
      const canon_channel_t* channel=NULL;
      int num = write_number[i];

      /* TODO optimize => move reorder code to do_print */
      for(x=0;x < pd->num_channels; x++){
	if(pd->channels[x].name == write_sequence[i]){
              channel = &(pd->channels[x]);
              break;
          }
      }
      if(channel){
        written += canon_write(v, pd, pd->caps,
                               channel->buf + channel->delay * pd->length /*buf_length[i]*/,
                               pd->length, num,
                               &(pd->emptylines), pd->out_width,
                               pd->left, channel->props->bits, channel->props->flags);
      } 
    }
  if (written)
    stp_zfwrite("\033\050\145\002\000\000\001", 7, 1, v);
  else
    pd->emptylines += 1;
}


/* write one multiraster block */
static void canon_write_block(stp_vars_t* v,canon_privdata_t* pd,unsigned char* start, unsigned char* end){
    unsigned int length = end - start;
    if(!length)
        return;
    stp_zfwrite("\033(F", 3, 1, v);
    stp_put16_le(length, v);
    stp_zfwrite((const char *)start, length, 1, v);
}


static void canon_write_multiraster(stp_vars_t *v,canon_privdata_t* pd,int y){
    int i;
    /*int raster_lines_per_block = pd->caps->raster_lines_per_block;*/
    int raster_lines_per_block = pd->mode->raster_lines_per_block;
    unsigned int max_length = 2*pd->buf_length_max * raster_lines_per_block;
    /* a new raster block begins */
    if(!(y % raster_lines_per_block)){
        if(y != 0){
            /* write finished blocks */
            for(i=0;i<pd->num_channels;i++)
                canon_write_block(v,pd,pd->comp_buf + i * max_length,pd->channels[i].comp_buf_offset);
        }
        /* reset start offsets */
        for(i=0;i<pd->num_channels;i++)
            pd->channels[i].comp_buf_offset = pd->comp_buf + i * max_length;
    }
    /* compress lines and add them to the buffer */
    for(i=0;i<pd->num_channels;i++){
       pd->channels[i].comp_buf_offset += canon_compress(v,pd, pd->channels[i].buf,pd->length,pd->left,pd->channels[i].comp_buf_offset,pd->channels[i].props->bits, pd->channels[i].props->flags);
       *(pd->channels[i].comp_buf_offset) = 0x80; /* terminate the line */
        ++pd->channels[i].comp_buf_offset;
    }
    if(y == pd->out_height - 1){
        /* we just compressed our last line */
        if(pd->out_height % raster_lines_per_block){
            /* but our raster block is not finished yet */
            int missing = raster_lines_per_block - (pd->out_height % raster_lines_per_block); /* calculate missing lines */
            for(i=0;i<pd->num_channels;i++){
                /* add missing empty lines and write blocks */
                int x;
                for(x=0;x < missing ; x++){
                  *(pd->channels[i].comp_buf_offset) = 0x80; /* terminate the line */
                  ++pd->channels[i].comp_buf_offset;
                }
                canon_write_block(v,pd,pd->comp_buf + i * max_length,pd->channels[i].comp_buf_offset);
            }
        }
    }
}


static void
canon_advance_paper(stp_vars_t *v, int advance)
{
  if ( advance > 0 )
    {
      int a0, a1, a2, a3;
      stp_deprintf(STP_DBG_CANON,"                      --advance paper %d\n", advance);
      a0 = advance         & 0xff;
      a1 = (advance >> 8)  & 0xff;
      a2 = (advance >> 16) & 0xff;
      a3 = (advance >> 24) & 0xff;
      stp_zprintf(v, "\033(e%c%c%c%c%c%c", 4, 0, a3, a2, a1, a0);
    }
}

static void
canon_flush_pass(stp_vars_t *v, int passno, int vertical_subpass)
{
  stp_lineoff_t        *lineoffs   = stp_get_lineoffsets_by_pass(v, passno);
  stp_lineactive_t     *lineactive = stp_get_lineactive_by_pass(v, passno);
  const stp_linebufs_t *bufs       = stp_get_linebases_by_pass(v, passno);
  stp_pass_t           *pass       = stp_get_pass_by_pass(v, passno);
  stp_linecount_t      *linecount  = stp_get_linecount_by_pass(v, passno);
  canon_privdata_t      *pd         = (canon_privdata_t *) stp_get_component_data(v, "Driver");
  int                    papershift = (pass->logicalpassstart - pd->last_pass_offset);

  int color, line, written = 0, linelength = 0, lines = 0;
  int idx[4]={3, 0, 1, 2}; /* color numbering is different between canon_write and weaving */

  stp_deprintf(STP_DBG_CANON,"canon_flush_pass: ----pass=%d,---- \n", passno);
  (pd->emptylines) = 0;

  for ( color = 0; color < pd->ncolors; color++ ) /* find max. linecount */
    {
      if ( linecount[0].v[color] > lines )
        lines = linecount[0].v[color];
    }

  for ( line = 0; line < lines; line++ )  /* go through each nozzle f that pass */
    {
      stp_deprintf(STP_DBG_CANON,"                      --line=%d\n", line);

      if ( written > 0 )
        canon_cmd(v,ESC28,0x65, 2, 0, 1); /* go to next nozzle*/
                                           /* if there was printed some data */

      written = 0;
      for ( color = 0; color < pd->ncolors; color++ )
        {
          if ( line < linecount[0].v[color] )  /* try only existing lines */
            {
              if ( lineactive[0].v[color] > 0 )
                {
                  linelength = lineoffs[0].v[color] / linecount[0].v[color];
/*                stp_deprintf(STP_DBG_CANON,"canon_flush_pass: linelength=%d, bufs[0].v[color]=%p,"
                  "bufs[0].v[color]+line * linelength=%p, empty=%d \n", linelength, bufs[0].v[color],
                   bufs[0].v[color] + line * linelength, (pd->emptylines));
*/
                  if ( pass->logicalpassstart - pd->last_pass_offset > 0 )
                    {
                      canon_advance_paper(v, papershift);
                      pd->last_pass_offset = pass->logicalpassstart;
                      if (pd->bidirectional)
                        {
                         pd->direction = (pd->direction +1) & 1;
                         canon_set_X72(v, pd->direction);
                         stp_deprintf(STP_DBG_CANON,"                      --set direction %d\n", pd->direction);
                        }
                    }

                  written += canon_write(v, pd, pd->caps,
                               (unsigned char *)(bufs[0].v[color] + line * linelength),
                               linelength, idx[color],
                               &(pd->emptylines), pd->out_width,
                               pd->left, pd->weave_bits[color],0);
                  if (written) stp_deprintf(STP_DBG_CANON,"                        --written color %d,\n", color);

                }
            }
        }

      if ( written == 0 ) /* count unused nozzles */
        (pd->emptylines) += 1;
    }

  for ( color = 0; color < pd->ncolors; color++ )
    {
      lineoffs[0].v[color] = 0;
      linecount[0].v[color] = 0;
    }
  stp_deprintf(STP_DBG_CANON,"                  --ended-- with empty=%d \n", (pd->emptylines));
}

static stp_family_t print_canon_module_data =
  {
    &print_canon_printfuncs,
    NULL
  };


static int
print_canon_module_init(void)
{
  return stp_family_register(print_canon_module_data.printer_list);
}


static int
print_canon_module_exit(void)
{
  return stp_family_unregister(print_canon_module_data.printer_list);
}


/* Module header */
#define stp_module_version print_canon_LTX_stp_module_version
#define stp_module_data print_canon_LTX_stp_module_data

stp_module_version_t stp_module_version = {0, 0};

stp_module_t stp_module_data =
  {
    "canon",
    VERSION,
    "Canon family driver",
    STP_MODULE_CLASS_FAMILY,
    NULL,
    print_canon_module_init,
    print_canon_module_exit,
    (void *) &print_canon_module_data
  };