summaryrefslogtreecommitdiff
path: root/src/cups/backend_shinkos1245.c
blob: cd0d34c34ec35d54b1be88b371287fec43489b37 (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
/*
 *   Shinko/Sinfonia CHC-S1245 CUPS backend -- libusb-1.0 version
 *
 *   (c) 2015-2018 Solomon Peachy <pizza@shaftnet.org>
 *
 *   Low-level documentation was provided by Sinfonia, Inc.  Thank you!
 *
 *   The latest version of this program can be found at:
 *
 *     http://git.shaftnet.org/cgit/selphy_print.git
 *
 *   This program is free software; you can redistribute it and/or modify it
 *   under the terms of the GNU General Public License as published by the Free
 *   Software Foundation; either version 2 of the License, or (at your option)
 *   any later version.
 *
 *   This program is distributed in the hope that it will be useful, but
 *   WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 *   or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 *   for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 *          [http://www.gnu.org/licenses/gpl-2.0.html]
 *
 *   SPDX-License-Identifier: GPL-2.0+
 *
 */

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

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

#define BACKEND shinkos1245_backend

#include "backend_common.h"

/* Structure of printjob header.  All fields are LITTLE ENDIAN */
struct s1245_printjob_hdr {
	uint32_t len1;   /* Fixed at 0x10 */
	uint32_t model;  /* Equal to the printer model (eg '1245' or '2145' decimal) */
	uint32_t unk2;   /* Null */
	uint32_t unk3;   /* Fixed at 0x01 */

	uint32_t len2;   /* Fixed at 0x64 */
	uint32_t unk5;   /* Null */
	uint32_t media;  /* Fixed at 0x10 */
	uint32_t unk6;   /* Null */

	uint32_t method; /* Print Method */
	uint32_t mode;   /* Print Mode */
	uint32_t unk7;   /* Null */
	 int32_t mattedepth; /* 0x7fffffff for glossy, 0x00 +- 25 for matte */

	uint32_t dust;   /* Dust control */
	uint32_t columns;
	uint32_t rows;
	uint32_t copies;

	uint32_t unk10;  /* Null */
	uint32_t unk11;  /* Null */
	uint32_t unk12;  /* Null */
	uint32_t unk13;  /* 0xceffffff */

	uint32_t unk14;  /* Null */
	uint32_t unk15;  /* 0xceffffff */
	uint32_t dpi; /* Fixed at '300' (decimal) */
	uint32_t unk16;  /* 0xceffffff */

	uint32_t unk17;  /* Null */
	uint32_t unk18;  /* 0xceffffff */
	uint32_t unk19;  /* Null */
	uint32_t unk20;  /* Null */

	uint32_t unk21;  /* Null */
} __attribute__((packed));

/* Printer data structures */
struct shinkos1245_cmd_hdr {
	uint8_t prefix; /* 0x03 */
	uint8_t hdr[4]; /* 0x1b 0x43 0x48 0x43 */
} __attribute__((packed));

/* Get Printer ID */
struct shinkos1245_cmd_getid {
	struct shinkos1245_cmd_hdr hdr;
	uint8_t cmd[1]; /* 0x12 */
	uint8_t pad[11];
} __attribute__((packed));

struct shinkos1245_resp_getid {
	uint8_t id;       /* 0x00 */
	uint8_t data[23]; /* padded with 0x20 (space) */
	uint8_t reserved[8]; // XXX actual serial number?
} __attribute__((packed));

/* Set Printer ID -- Returns Status */
struct shinkos1245_cmd_setid {
	struct shinkos1245_cmd_hdr hdr;
	uint8_t cmd[2];   /* 0x0a 0x22 */
	uint8_t id;       /* 0x00 */
	uint8_t data[23]; /* pad with 0x20 (space) */
} __attribute__((packed));

/* Print -- Returns Status */
struct shinkos1245_cmd_print {
	struct shinkos1245_cmd_hdr hdr;
	uint8_t  cmd[2];   /* 0x0a 0x00 */
	uint8_t  id;       /* 1-255 */
	uint16_t count;    /* # Copies in BCD, 1-9999 */
	uint16_t columns;  /* Fixed at 2446 */
	uint16_t rows;
	uint8_t  media;    /* Fixed at 0x10 */
	uint8_t  mode;     /* dust removal and lamination mode */
	uint8_t  combo;    /* aka "print method" in the spool file */
} __attribute__((packed));

/* Get Status */
struct shinkos1245_cmd_getstatus {
	struct shinkos1245_cmd_hdr hdr;
	uint8_t cmd[1];   /* 0x03 */
	uint8_t pad[10];
} __attribute__((packed));

struct shinkos1245_resp_status {
	uint8_t  code;
	uint8_t  print_status;
	struct {
		uint8_t  status1;
		uint32_t status2; /* BE */
		uint8_t  error;
	} __attribute__((packed)) state;
	struct {
		uint32_t lifetime;  /* BE */
		uint32_t maint;     /* BE */
		uint32_t media;     /* BE */
		uint32_t cutter;    /* BE */
		uint8_t  reserved;
		uint8_t  ver_boot;
		uint8_t  ver_ctrl;
		uint8_t  control_flag; // 0x00 == epson, 0x01 == cypress
	} __attribute__((packed)) counters;
	struct {
		uint16_t main_boot;
		uint16_t main_control;
		uint16_t dsp_boot;
		uint16_t dsp_control;
	} __attribute__((packed)) versions;
	struct {
		uint8_t  bank1_id;
		uint8_t  bank2_id;
		uint16_t bank1_remain;   /* BE */
		uint16_t bank1_complete; /* BE */
		uint16_t bank1_spec;     /* BE */
		uint16_t bank2_remain;   /* BE */
		uint16_t bank2_complete; /* BE */
		uint16_t bank2_spec;     /* BE */
	} __attribute__((packed)) counters2;
	uint8_t curve_status;
} __attribute__((packed));

enum {
	CMD_CODE_OK = 1,
	CMD_CODE_BAD = 2,
};

enum {
	STATUS_PRINTING = 1,
	STATUS_IDLE = 2,
};

enum {
	STATE_STATUS1_STANDBY = 1,
	STATE_STATUS1_ERROR = 2,
	STATE_STATUS1_WAIT = 3,
};

#define STATE_STANDBY_STATUS2 0x0

enum {
	WAIT_STATUS2_INIT = 0,
	WAIT_STATUS2_RIBBON = 1,
	WAIT_STATUS2_THERMAL = 2,
	WAIT_STATUS2_OPERATING = 3,
	WAIT_STATUS2_BUSY = 4,
};


#define ERROR_STATUS2_CTRL_CIRCUIT   (0x80000000)
#define ERROR_STATUS2_MECHANISM_CTRL (0x40000000)
#define ERROR_STATUS2_SENSOR         (0x00002000)
#define ERROR_STATUS2_COVER_OPEN     (0x00001000)
#define ERROR_STATUS2_TEMP_SENSOR    (0x00000200)
#define ERROR_STATUS2_PAPER_JAM      (0x00000100)
#define ERROR_STATUS2_PAPER_EMPTY    (0x00000040)
#define ERROR_STATUS2_RIBBON_ERR     (0x00000010)

enum {
	CTRL_CIR_ERROR_EEPROM1  = 0x01,
	CTRL_CIR_ERROR_EEPROM2  = 0x02,
	CTRL_CIR_ERROR_DSP      = 0x04,
	CTRL_CIR_ERROR_CRC_MAIN = 0x06,
	CTRL_CIR_ERROR_DL_MAIN  = 0x07,
	CTRL_CIR_ERROR_CRC_DSP  = 0x08,
	CTRL_CIR_ERROR_DL_DSP   = 0x09,
	CTRL_CIR_ERROR_ASIC     = 0x0a,
	CTRL_CIR_ERROR_DRAM     = 0x0b,
	CTRL_CIR_ERROR_DSPCOMM  = 0x29,
};

enum {
	MECH_ERROR_HEAD_UP            = 0x01,
	MECH_ERROR_HEAD_DOWN          = 0x02,
	MECH_ERROR_MAIN_PINCH_UP      = 0x03,
	MECH_ERROR_MAIN_PINCH_DOWN    = 0x04,
	MECH_ERROR_SUB_PINCH_UP       = 0x05,
	MECH_ERROR_SUB_PINCH_DOWN     = 0x06,
	MECH_ERROR_FEEDIN_PINCH_UP    = 0x07,
	MECH_ERROR_FEEDIN_PINCH_DOWN  = 0x08,
	MECH_ERROR_FEEDOUT_PINCH_UP   = 0x09,
	MECH_ERROR_FEEDOUT_PINCH_DOWN = 0x0a,
	MECH_ERROR_CUTTER_LR          = 0x0b,
	MECH_ERROR_CUTTER_RL          = 0x0c,
};

enum {
	SENSOR_ERROR_CUTTER           = 0x05,
	SENSOR_ERROR_HEAD_DOWN        = 0x09,
	SENSOR_ERROR_HEAD_UP          = 0x0a,
	SENSOR_ERROR_MAIN_PINCH_DOWN  = 0x0b,
	SENSOR_ERROR_MAIN_PINCH_UP    = 0x0c,
	SENSOR_ERROR_FEED_PINCH_DOWN  = 0x0d,
	SENSOR_ERROR_FEED_PINCH_UP    = 0x0e,
	SENSOR_ERROR_EXIT_PINCH_DOWN  = 0x0f,
	SENSOR_ERROR_EXIT_PINCH_UP    = 0x10,
	SENSOR_ERROR_LEFT_CUTTER      = 0x11,
	SENSOR_ERROR_RIGHT_CUTTER     = 0x12,
	SENSOR_ERROR_CENTER_CUTTER    = 0x13,
	SENSOR_ERROR_UPPER_CUTTER     = 0x14,
	SENSOR_ERROR_PAPER_FEED_COVER = 0x15,
};

enum {
	TEMP_SENSOR_ERROR_HEAD_HIGH = 0x01,
	TEMP_SENSOR_ERROR_HEAD_LOW  = 0x02,
	TEMP_SENSOR_ERROR_ENV_HIGH  = 0x03,
	TEMP_SENSOR_ERROR_ENV_LOW   = 0x04,
};

enum {
	COVER_OPEN_ERROR_UPPER = 0x01,
	COVER_OPEN_ERROR_LOWER = 0x02,
};

enum {
	PAPER_EMPTY_ERROR = 0x00,
};

enum {
	RIBBON_ERROR = 0x00,
};

enum {
	CURVE_TABLE_STATUS_INITIAL = 0x00,
	CURVE_TABLE_STATUS_USERSET = 0x01,
	CURVE_TABLE_STATUS_CURRENT = 0x02,
};

/* Query media info */
struct shinkos1245_cmd_getmedia {
	struct shinkos1245_cmd_hdr hdr;
	uint8_t cmd[1];   /* 0x1a/0x2a/0x3a for A/B/C */
	uint8_t pad[10];
} __attribute__((packed));

struct shinkos1245_mediadesc {
	uint8_t  code;  /* Fixed at 0x10 */
	uint16_t columns; /* BE */
	uint16_t rows;    /* BE */
	uint8_t  type;       /* MEDIA_TYPE_* */
	uint8_t  print_type; /* aka "print method" in the spool file */
	uint8_t  reserved[3];
} __attribute__((packed));

#define NUM_MEDIAS 5 /* Maximum per message */

struct shinkos1245_resp_media {
	uint8_t  code;
	uint8_t  reserved[6];
	uint8_t  count;  /* 1-5? */
	struct shinkos1245_mediadesc data[NUM_MEDIAS];
} __attribute__((packed));

enum {
	MEDIA_TYPE_UNKNOWN = 0x00,
	MEDIA_TYPE_PAPER = 0x01,
};

enum {
	PRINT_TYPE_STANDARD = 0x00,
	PRINT_TYPE_8x5_2up  = 0x01,
	PRINT_TYPE_8x4_2up  = 0x02,
	PRINT_TYPE_8x6_8x4  = 0x03,
	PRINT_TYPE_8x5      = 0x04,
	PRINT_TYPE_8x4      = 0x05,
	PRINT_TYPE_8x6      = 0x06,
	PRINT_TYPE_8x6_2up  = 0x07,
	PRINT_TYPE_8x4_3up  = 0x08,
	PRINT_TYPE_8x8      = 0x09,
};

/* Cancel Job -- returns Status */
struct shinkos1245_cmd_canceljob {
	struct shinkos1245_cmd_hdr hdr;
	uint8_t cmd[1];   /* 0x13 */
	uint8_t id;       /* 1-255 */
	uint8_t pad[9];
} __attribute__((packed));

/* Reset printer -- returns Status */
struct shinkos1245_cmd_reset {
	struct shinkos1245_cmd_hdr hdr;
	uint8_t cmd[1];   /* 0xc0 */
	uint8_t pad[10];
} __attribute__((packed));

/* Tone curve manipulation -- returns Status */
struct shinkos1245_cmd_tone {
	struct shinkos1245_cmd_hdr hdr;
	uint8_t cmd[1];   /* 0xc0 */
	uint8_t tone[4];  /* 0x54 0x4f 0x4e 0x45 */
	uint8_t cmd2[1];  /* 0x72/0x77/0x65/0x20 for read/write/end/data */
	union {
		struct {
			uint8_t tone_table;
			uint8_t param_table;
			uint8_t pad[3];
		} read_write;
		struct {
			uint8_t pad[5];
		} end_data;
	};
} __attribute__((packed));

enum {
	TONE_TABLE_STANDARD = 0,
	TONE_TABLE_USER = 1,
	TONE_TABLE_CURRENT = 2,
};
enum {
	PARAM_TABLE_STANDARD = 1,
	PARAM_TABLE_FINE = 2,
};

#define TONE_CURVE_SIZE 1536
#define TONE_CURVE_DATA_BLOCK_SIZE 64

/* Query Model information */
struct shinkos1245_cmd_getmodel {
	struct shinkos1245_cmd_hdr hdr;
	uint8_t cmd[1];   /* 0x02 */
	uint8_t pad[10];
} __attribute__((packed));

struct shinkos1245_resp_getmodel {
	uint8_t vendor_id[4];
	uint8_t product_id[4];
	uint8_t strings[40];
} __attribute__((packed));


/* Query and Set Matte info, returns a Matte response */
struct shinkos1245_cmd_getmatte {
	struct shinkos1245_cmd_hdr hdr;
	uint8_t cmd[1]; /* 0x20 */
	uint8_t mode;   /* Fixed at 0x00 */
	uint8_t pad[9];
} __attribute__((packed));

struct shinkos1245_cmd_setmatte {
	struct shinkos1245_cmd_hdr hdr;
	uint8_t cmd[1]; /* 0x21 */
	uint8_t mode;   /* Fixed at 0x00 */
	 int8_t level;  /* -25->+25 */
	uint8_t pad[8];
} __attribute__((packed));

struct shinkos1245_resp_matte {
	uint8_t code;
	uint8_t mode;
	 int8_t level;
	uint8_t reserved[4];
} __attribute__((packed));

#define MATTE_MODE_MATTE 0x00

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

	int copies;
};

struct shinkos1245_ctx {
	struct libusb_device_handle *dev;
	uint8_t endp_up;
	uint8_t endp_down;
	int type;

	uint8_t jobid;

	struct s1245_printjob_hdr hdr;

	struct shinkos1245_mediadesc medias[15];
	int num_medias;
	int media_8x12;

	struct marker marker;

	int tonecurve;
};

enum {
	S_IDLE = 0,
	S_PRINTER_READY_CMD,
	S_PRINTER_SENT_DATA,
	S_FINISHED,
};


/* Basic printer I/O stuffs */
static void shinkos1245_fill_hdr(struct shinkos1245_cmd_hdr *hdr)
{
	hdr->prefix = 0x03;
	hdr->hdr[0] = 0x1b;
	hdr->hdr[1] = 0x43;
	hdr->hdr[2] = 0x48;
	hdr->hdr[3] = 0x43;
}

static int shinkos1245_do_cmd(struct shinkos1245_ctx *ctx,
			      void *cmd, int cmd_len,
			      void *resp, int resp_len,
			      int *actual_len)
{
	int ret;

	/* Write command */
	if ((ret = send_data(ctx->dev, ctx->endp_down,
			     cmd, cmd_len)))
		return (ret < 0) ? ret : -99;

	/* Read response */
	ret = read_data(ctx->dev, ctx->endp_up,
			resp, resp_len, actual_len);
	if (ret < 0)
		return ret;
	if (*actual_len < resp_len) {
		ERROR("Short read! (%d/%d))\n", *actual_len, resp_len);
		return -99;
	}

	return ret;
}

static int shinkos1245_get_status(struct shinkos1245_ctx *ctx,
				  struct shinkos1245_resp_status *resp)
{
	struct shinkos1245_cmd_getstatus cmd;
	int ret, num;

	shinkos1245_fill_hdr(&cmd.hdr);
	cmd.cmd[0] = 0x03;
	memset(cmd.pad, 0, sizeof(cmd.pad));

	ret = shinkos1245_do_cmd(ctx, &cmd, sizeof(cmd),
				resp, sizeof(*resp), &num);
	if (ret < 0) {
		ERROR("Failed to execute GET_STATUS command\n");
		return ret;
	}
	if (resp->code != CMD_CODE_OK) {
		ERROR("Bad return code on GET_STATUS (%02x)\n",
		      resp->code);
		return -99;
	}

	return 0;
}

static int shinkos1245_get_media(struct shinkos1245_ctx *ctx)
{
	struct shinkos1245_cmd_getmedia cmd;
	struct shinkos1245_resp_media resp;
	int i, j;
	int ret = 0, num;

	shinkos1245_fill_hdr(&cmd.hdr);
	memset(cmd.pad, 0, sizeof(cmd.pad));
	ctx->media_8x12 = 0;
	for (i = 1 ; i <= 3 ; i++) {
		cmd.cmd[0] = 0x0a | (i << 4);

		ret = shinkos1245_do_cmd(ctx, &cmd, sizeof(cmd),
					 &resp, sizeof(resp), &num);
		if (ret < 0) {
			ERROR("Failed to execute GET_MEDIA command\n");
			return ret;
		}
		if (resp.code != CMD_CODE_OK) {
			ERROR("Bad return code on GET_MEDIA (%02x)\n",
			      resp.code);
			return -99;
		}

		/* Store media info */
		for (j = 0; j < NUM_MEDIAS && ctx->num_medias < resp.count ; j++) {
			ctx->medias[ctx->num_medias].code = resp.data[j].code;
			ctx->medias[ctx->num_medias].columns = be16_to_cpu(resp.data[j].columns);
			ctx->medias[ctx->num_medias].rows = be16_to_cpu(resp.data[j].rows);
			ctx->medias[ctx->num_medias].type = resp.data[j].type;
			ctx->medias[ctx->num_medias].print_type = resp.data[j].print_type;
			ctx->num_medias++;

			if (ctx->medias[i].rows >= 3636)
				ctx->media_8x12 = 1;
		}

		/* Once we've parsed them all.. we're done */
		if (ctx->num_medias == resp.count)
			break;
	}
	return ret;
}

static int shinkos1245_get_printerid(struct shinkos1245_ctx *ctx,
				     struct shinkos1245_resp_getid *resp)
{
	struct shinkos1245_cmd_getid cmd;
	int ret, num;

	shinkos1245_fill_hdr(&cmd.hdr);
	cmd.cmd[0] = 0x12;
	memset(cmd.pad, 0, sizeof(cmd.pad));

	ret = shinkos1245_do_cmd(ctx, &cmd, sizeof(cmd),
				resp, sizeof(*resp), &num);
	if (ret < 0) {
		ERROR("Failed to execute GET_PRINTERID command\n");
		return ret;
	}

	return 0;
}

static int shinkos1245_set_printerid(struct shinkos1245_ctx *ctx,
				     char *id)
{
	struct shinkos1245_cmd_setid cmd;
	struct shinkos1245_resp_status sts;

	int ret, num;
	int i;

	shinkos1245_fill_hdr(&cmd.hdr);
	cmd.cmd[0] = 0x0a;
	cmd.cmd[1] = 0x22;

	for (i = 0 ; i < (int)sizeof(cmd.data) ; i++) {
		if (*id)
			cmd.data[i] = (uint8_t) *id++;
		else
			cmd.data[i] = ' ';
	}
	ret = shinkos1245_do_cmd(ctx, &cmd, sizeof(cmd),
				 &sts, sizeof(sts), &num);
	if (ret < 0) {
		ERROR("Failed to execute SET_PRINTERID command\n");
		return ret;
	}
	if (sts.code != CMD_CODE_OK) {
		ERROR("Bad return code on SET_PRINTERID command\n");
		return -99;
	}
	return 0;
}

static int shinkos1245_canceljob(struct shinkos1245_ctx *ctx,
				 int id)
{
	struct shinkos1245_cmd_canceljob cmd;
	struct shinkos1245_resp_status sts;

	int ret, num;

	shinkos1245_fill_hdr(&cmd.hdr);
	cmd.cmd[0] = 0x13;
	cmd.id = id;

	ret = shinkos1245_do_cmd(ctx, &cmd, sizeof(cmd),
				 &sts, sizeof(sts), &num);
	if (ret < 0) {
		ERROR("Failed to execute CANCELJOB command\n");
		return ret;
	}
	if (sts.code != CMD_CODE_OK) {
		ERROR("Bad return code on CANCELJOB command\n");
		return -99;
	}
	return 0;
}

static int shinkos1245_reset(struct shinkos1245_ctx *ctx)
{
	struct shinkos1245_cmd_reset cmd;
	struct shinkos1245_resp_status sts;

	int ret, num;

	shinkos1245_fill_hdr(&cmd.hdr);
	cmd.cmd[0] = 0xc0;

	ret = shinkos1245_do_cmd(ctx, &cmd, sizeof(cmd),
				 &sts, sizeof(sts), &num);
	if (ret < 0) {
		ERROR("Failed to execute RESET command\n");
		return ret;
	}
	if (sts.code != CMD_CODE_OK) {
		ERROR("Bad return code on RESET command\n");
		return -99;
	}
	return 0;
}


static int shinkos1245_set_matte(struct shinkos1245_ctx *ctx,
				 int intensity)
{
	struct shinkos1245_cmd_setmatte cmd;
	struct shinkos1245_resp_matte sts;

	int ret, num;

	shinkos1245_fill_hdr(&cmd.hdr);
	cmd.cmd[0] = 0x21;
	cmd.mode = MATTE_MODE_MATTE;
	cmd.level = intensity;

	ret = shinkos1245_do_cmd(ctx, &cmd, sizeof(cmd),
				 &sts, sizeof(sts), &num);
	if (ret < 0) {
		ERROR("Failed to execute SET_MATTE command\n");
		return ret;
	}
	if (sts.code == CMD_CODE_OK)
		return 0;
	if (sts.code == CMD_CODE_BAD)
		return 1;

	ERROR("Bad return code (%02x) on SET_MATTE command\n", sts.code);
	return -99;
}

static int shinkos1245_get_matte(struct shinkos1245_ctx *ctx,
				 int *intensity)
{
	struct shinkos1245_cmd_getmatte cmd;
	struct shinkos1245_resp_matte sts;

	int ret, num;

	shinkos1245_fill_hdr(&cmd.hdr);
	cmd.cmd[0] = 0x20;
	cmd.mode = MATTE_MODE_MATTE;

	ret = shinkos1245_do_cmd(ctx, &cmd, sizeof(cmd),
				 &sts, sizeof(sts), &num);
	if (ret < 0) {
		ERROR("Failed to execute GET_MATTE command\n");
		return ret;
	}
	if (sts.code != CMD_CODE_OK) {
		ERROR("Bad return code (%02x) on GET_MATTE command\n", sts.code);
		return -99;
	}
	*intensity = sts.level;

	return 0;
}


/* Structure dumps */
static char *shinkos1245_status_str(struct shinkos1245_resp_status *resp)
{
	switch(resp->state.status1) {
	case STATE_STATUS1_STANDBY:
		return "Standby (Ready)";
	case STATE_STATUS1_WAIT:
		switch (resp->state.status2) {
		case WAIT_STATUS2_INIT:
			return "Wait (Initializing)";
		case WAIT_STATUS2_RIBBON:
			return "Wait (Ribbon Winding)";
		case WAIT_STATUS2_THERMAL:
			return "Wait (Thermal Protection)";
		case WAIT_STATUS2_OPERATING:
			return "Wait (Operating)";
		case WAIT_STATUS2_BUSY:
			return "Wait (Busy)";
		default:
			return "Wait (Unknown)";
		}
	case STATE_STATUS1_ERROR:
		switch (resp->state.status2) {
		case ERROR_STATUS2_CTRL_CIRCUIT:
			switch (resp->state.error) {
			case CTRL_CIR_ERROR_EEPROM1:
				return "Error (EEPROM1)";
			case CTRL_CIR_ERROR_EEPROM2:
				return "Error (EEPROM2)";
			case CTRL_CIR_ERROR_DSP:
				return "Error (DSP)";
			case CTRL_CIR_ERROR_CRC_MAIN:
				return "Error (Main CRC)";
			case CTRL_CIR_ERROR_DL_MAIN:
				return "Error (Main Download)";
			case CTRL_CIR_ERROR_CRC_DSP:
				return "Error (DSP CRC)";
			case CTRL_CIR_ERROR_DL_DSP:
				return "Error (DSP Download)";
			case CTRL_CIR_ERROR_ASIC:
				return "Error (ASIC)";
			case CTRL_CIR_ERROR_DRAM:
				return "Error (DRAM)";
			case CTRL_CIR_ERROR_DSPCOMM:
				return "Error (DSP Communincation)";
			default:
				return "Error (Unknown Circuit)";
			}
		case ERROR_STATUS2_MECHANISM_CTRL:
			switch (resp->state.error) {
			case MECH_ERROR_HEAD_UP:
				return "Error (Head Up Mechanism)";
			case MECH_ERROR_HEAD_DOWN:
				return "Error (Head Down Mechanism)";
			case MECH_ERROR_MAIN_PINCH_UP:
				return "Error (Main Pinch Up Mechanism)";
			case MECH_ERROR_MAIN_PINCH_DOWN:
				return "Error (Main Pinch Down Mechanism)";
			case MECH_ERROR_SUB_PINCH_UP:
				return "Error (Sub Pinch Up Mechanism)";
			case MECH_ERROR_SUB_PINCH_DOWN:
				return "Error (Sub Pinch Down Mechanism)";
			case MECH_ERROR_FEEDIN_PINCH_UP:
				return "Error (Feed-in Pinch Up Mechanism)";
			case MECH_ERROR_FEEDIN_PINCH_DOWN:
				return "Error (Feed-in Pinch Down Mechanism)";
			case MECH_ERROR_FEEDOUT_PINCH_UP:
				return "Error (Feed-out Pinch Up Mechanism)";
			case MECH_ERROR_FEEDOUT_PINCH_DOWN:
				return "Error (Feed-out Pinch Down Mechanism)";
			case MECH_ERROR_CUTTER_LR:
				return "Error (Left->Right Cutter)";
			case MECH_ERROR_CUTTER_RL:
				return "Error (Right->Left Cutter)";
			default:
				return "Error (Unknown Mechanism)";
			}
		case ERROR_STATUS2_SENSOR:
			switch (resp->state.error) {
			case SENSOR_ERROR_CUTTER:
				return "Error (Cutter Sensor)";
			case SENSOR_ERROR_HEAD_DOWN:
				return "Error (Head Down Sensor)";
			case SENSOR_ERROR_HEAD_UP:
				return "Error (Head Up Sensor)";
			case SENSOR_ERROR_MAIN_PINCH_DOWN:
				return "Error (Main Pinch Down Sensor)";
			case SENSOR_ERROR_MAIN_PINCH_UP:
				return "Error (Main Pinch Up Sensor)";
			case SENSOR_ERROR_FEED_PINCH_DOWN:
				return "Error (Feed Pinch Down Sensor)";
			case SENSOR_ERROR_FEED_PINCH_UP:
				return "Error (Feed Pinch Up Sensor)";
			case SENSOR_ERROR_EXIT_PINCH_DOWN:
				return "Error (Exit Pinch Up Sensor)";
			case SENSOR_ERROR_EXIT_PINCH_UP:
				return "Error (Exit Pinch Up Sensor)";
			case SENSOR_ERROR_LEFT_CUTTER:
				return "Error (Left Cutter Sensor)";
			case SENSOR_ERROR_RIGHT_CUTTER:
				return "Error (Right Cutter Sensor)";
			case SENSOR_ERROR_CENTER_CUTTER:
				return "Error (Center Cutter Sensor)";
			case SENSOR_ERROR_UPPER_CUTTER:
				return "Error (Upper Cutter Sensor)";
			case SENSOR_ERROR_PAPER_FEED_COVER:
				return "Error (Paper Feed Cover)";
			default:
				return "Error (Unknown Sensor)";
			}
		case ERROR_STATUS2_COVER_OPEN:
			switch (resp->state.error) {
			case COVER_OPEN_ERROR_UPPER:
				return "Error (Upper Cover Open)";
			case COVER_OPEN_ERROR_LOWER:
				return "Error (Lower Cover Open)";
			default:
				return "Error (Unknown Cover Open)";
			}
		case ERROR_STATUS2_TEMP_SENSOR:
			switch (resp->state.error) {
			case TEMP_SENSOR_ERROR_HEAD_HIGH:
				return "Error (Head Temperature High)";
			case TEMP_SENSOR_ERROR_HEAD_LOW:
				return "Error (Head Temperature Low)";
			case TEMP_SENSOR_ERROR_ENV_HIGH:
				return "Error (Environmental Temperature High)";
			case TEMP_SENSOR_ERROR_ENV_LOW:
				return "Error (Environmental Temperature Low)";
			default:
				return "Error (Unknown Temperature)";
			}
		case ERROR_STATUS2_PAPER_JAM:
			return "Error (Paper Jam)";
		case ERROR_STATUS2_PAPER_EMPTY:
			return "Error (Paper Empty)";
		case ERROR_STATUS2_RIBBON_ERR:
			return "Error (Ribbon)";
		default:
			return "Error (Unknown)";
		}
	default:
		return "Unknown!";
	}
}

static char* shinkos1245_tonecurves(int type, int table)
{
	switch (type) {
	case TONE_TABLE_STANDARD:
		switch (table) {
		case PARAM_TABLE_STANDARD:
			return "Standard/Standard";
		case PARAM_TABLE_FINE:
			return "Standard/Fine";
		default:
			return "Standard/Unknown";
		}
	case TONE_TABLE_USER:
		switch (table) {
		case PARAM_TABLE_STANDARD:
			return "User/Standard";
		case PARAM_TABLE_FINE:
			return "User/Fine";
		default:
			return "User/Unknown";
		}
	case TONE_TABLE_CURRENT:
		switch (table) {
		case PARAM_TABLE_STANDARD:
			return "Current/Standard";
		case PARAM_TABLE_FINE:
			return "Current/Fine";
		default:
			return "Current/Unknown";
		}
	default:
		return "Unknown";
	}
}

static void shinkos1245_dump_status(struct shinkos1245_ctx *ctx,
				    struct shinkos1245_resp_status *sts)
{
	char *detail;
	switch (sts->print_status) {
	case STATUS_PRINTING:
		detail = "Printing";
		break;
	case STATUS_IDLE:
		detail = "Idle";
		break;
	default:
		detail = "Unknown";
		break;
	}
	INFO("Printer Status:  %s\n", detail);

	/* Byteswap */
	sts->state.status2 = be32_to_cpu(sts->state.status2);

	INFO("Printer State: %s # %02x %08x %02x\n",
	     shinkos1245_status_str(sts),
	     sts->state.status1, sts->state.status2, sts->state.error);
	INFO("Counters:\n");
	INFO("\tLifetime     :  %u\n", be32_to_cpu(sts->counters.lifetime));
	INFO("\tThermal Head :  %u\n", be32_to_cpu(sts->counters.maint));
	INFO("\tMedia        :  %u\n", be32_to_cpu(sts->counters.media));
	INFO("\tRemaining    :  %u\n", ctx->marker.levelmax - be32_to_cpu(sts->counters.media));
	INFO("\tCutter       :  %u\n", be32_to_cpu(sts->counters.cutter));
	INFO("Versions:\n");
	INFO("\tUSB Boot    : %u\n", sts->counters.ver_boot);
	INFO("\tUSB Control : %u\n", sts->counters.ver_ctrl);
	INFO("\tMain Boot   : %u\n", be16_to_cpu(sts->versions.main_boot));
	INFO("\tMain Control: %u\n", be16_to_cpu(sts->versions.main_control));
	INFO("\tDSP Boot    : %u\n", be16_to_cpu(sts->versions.dsp_boot));
	INFO("\tDSP Control : %u\n", be16_to_cpu(sts->versions.dsp_control));

//	INFO("USB TypeFlag: %02x\n", sts->counters.control_flag);

	INFO("Bank 1 ID: %u\n", sts->counters2.bank1_id);
	INFO("\tPrints:  %d/%d complete\n",
	     be16_to_cpu(sts->counters2.bank1_complete),
	     be16_to_cpu(sts->counters2.bank1_spec));
	INFO("Bank 2 ID: %u\n", sts->counters2.bank2_id);
	INFO("\tPrints:  %d/%d complete\n",
	     be16_to_cpu(sts->counters2.bank2_complete),
	     be16_to_cpu(sts->counters2.bank2_spec));

	switch (sts->curve_status) {
	case CURVE_TABLE_STATUS_INITIAL:
		detail = "Initial/Default";
		break;
	case CURVE_TABLE_STATUS_USERSET:
		detail = "User Stored";
		break;
	case CURVE_TABLE_STATUS_CURRENT:
		detail = "Current";
		break;
	default:
		detail = "Unknown";
		break;
	}
	INFO("Tone Curve Status: %s\n", detail);
}

static void shinkos1245_dump_media(struct shinkos1245_mediadesc *medias,
				   int media_8x12,
				   int count)
{
	int i;

	INFO("Loaded media type: %s\n", media_8x12 ? "8x12" : "8x10");
	INFO("Supported print sizes: %d\n", count);

	for (i = 0 ; i < count ; i++) {
		INFO("\t %02x: %04u*%04u (%02x/%02u)\n",
		     medias[i].print_type,
		     medias[i].columns,
		     medias[i].rows,
		     medias[i].type, medias[i].print_type);
	}
}

static int get_tonecurve(struct shinkos1245_ctx *ctx, int type, int table, char *fname)
{
	int ret = 0, num, remaining;
	uint8_t *data, *ptr;

	struct shinkos1245_cmd_tone cmd;
	struct shinkos1245_resp_status resp;

	INFO("Dump %s Tone Curve to '%s'\n", shinkos1245_tonecurves(type, table), fname);

	/* Issue a tone_read_start */
	shinkos1245_fill_hdr(&cmd.hdr);
	cmd.cmd[0] = 0x0c;
	cmd.tone[0] = 0x54;
	cmd.tone[1] = 0x4f;
	cmd.tone[2] = 0x4e;
	cmd.tone[3] = 0x45;
	cmd.cmd2[0] = 0x72;
	cmd.read_write.tone_table = type;
	cmd.read_write.param_table = table;

	ret = shinkos1245_do_cmd(ctx, &cmd, sizeof(cmd),
				&resp, sizeof(resp), &num);

	if (ret < 0) {
		ERROR("Failed to execute TONE_READ command\n");
		return ret;
	}
	if (resp.code != CMD_CODE_OK) {
		ERROR("Bad return code on TONE_READ (%02x)\n",
		      resp.code);
		return -99;
	}

	/* Get the data out */
	remaining = TONE_CURVE_SIZE;
	data = malloc(remaining);
	if (!data) {
		ERROR("Memory Allocation Failure!\n");
		return -11;
	}
	ptr = data;

	while(remaining) {
		/* Issue a tone_data message */
		cmd.cmd2[0] = 0x20;

		ret = shinkos1245_do_cmd(ctx, &cmd, sizeof(cmd),
					 &resp, sizeof(resp), &num);

		if (ret < 0) {
			ERROR("Failed to execute TONE_DATA command\n");
			goto done;
		}
		if (resp.code != CMD_CODE_OK) {
			ERROR("Bad return code on TONE_DATA (%02x)\n",
			      resp.code);
			ret = -99;
			goto done;
		}

		/* And read back 64-bytes of data */
		ret = read_data(ctx->dev, ctx->endp_up,
				ptr, TONE_CURVE_DATA_BLOCK_SIZE, &num);
		if (num != TONE_CURVE_DATA_BLOCK_SIZE) {
			ret = -99;
			goto done;
		}
		if (ret < 0)
			goto done;
		ptr += num;
		remaining -= num;
	}

	/* Issue a tone_end */
	cmd.cmd2[0] = 0x65;
	ret = shinkos1245_do_cmd(ctx, &cmd, sizeof(cmd),
				&resp, sizeof(resp), &num);

	if (ret < 0) {
		ERROR("Failed to execute TONE_END command\n");
		goto done;
	}
	if (resp.code != CMD_CODE_OK) {
		ERROR("Bad return code on TONE_END (%02x)\n",
		      resp.code);
		ret = -99;
		goto done;
	}

	/* Open file and write it out */
	{
		int tc_fd = open(fname, O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR);
		if (tc_fd < 0) {
			ret = tc_fd;
			goto done;
		}

		ret = write(tc_fd, data, TONE_CURVE_SIZE);
		if (ret < 0)
			goto done;
		close(tc_fd);
	}

done:
	free(data);

	return ret;
}

static int set_tonecurve(struct shinkos1245_ctx *ctx, int type, int table, char *fname)
{
	int ret = 0, num, remaining;
	uint8_t *data, *ptr;

	struct shinkos1245_cmd_tone cmd;
	struct shinkos1245_resp_status resp;

	INFO("Read %d/%d Tone Curve from '%s'\n", type, table, fname);

	/* Allocate space */
	remaining = TONE_CURVE_SIZE;
	data = malloc(remaining);
	if (!data) {
		ERROR("Memory Allocation Failure!\n");
		return -11;
	}
	ptr = data;

	/* Open file and read it in */
	{
		int tc_fd = open(fname, O_RDONLY);
		if (tc_fd < 0) {
			ret = tc_fd;
			goto done;
		}

		ret = read(tc_fd, data, TONE_CURVE_SIZE);
		if (ret < 0) {
			close(tc_fd);
			goto done;
		}

		close(tc_fd);
	}

	/* Issue a tone_write_start */
	shinkos1245_fill_hdr(&cmd.hdr);
	cmd.cmd[0] = 0x0c;
	cmd.tone[0] = 0x54;
	cmd.tone[1] = 0x4f;
	cmd.tone[2] = 0x4e;
	cmd.tone[3] = 0x45;
	cmd.cmd2[0] = 0x77;
	cmd.read_write.tone_table = type;
	cmd.read_write.param_table = table;

	ret = shinkos1245_do_cmd(ctx, &cmd, sizeof(cmd),
				&resp, sizeof(resp), &num);

	if (ret < 0) {
		ERROR("Failed to execute TONE_WRITE command\n");
		goto done;
	}
	if (resp.code != CMD_CODE_OK) {
		ERROR("Bad return code on TONE_WRITE (%02x)\n",
		      resp.code);
		ret = -99;
		goto done;
	}

	while(remaining) {
		/* Issue a tone_data message */
		cmd.cmd2[0] = 0x20;

		ret = shinkos1245_do_cmd(ctx, &cmd, sizeof(cmd),
					 &resp, sizeof(resp), &num);

		if (ret < 0) {
			ERROR("Failed to execute TONE_DATA command\n");
			goto done;
		}
		if (resp.code != CMD_CODE_OK) {
			ERROR("Bad return code on TONE_DATA (%02x)\n",
			      resp.code);
			ret = -99;
			goto done;
		}

		/* Write 64-bytes of data */
		ret = send_data(ctx->dev, ctx->endp_up,
				ptr, TONE_CURVE_DATA_BLOCK_SIZE);
		if (ret < 0)
			goto done;
		ptr += num;
		remaining -= num;
	}

	/* Issue a tone_end */
	cmd.cmd2[0] = 0x65;
	ret = shinkos1245_do_cmd(ctx, &cmd, sizeof(cmd),
				&resp, sizeof(resp), &num);

	if (ret < 0) {
		ERROR("Failed to execute TONE_END command\n");
		goto done;
	}
	if (resp.code != CMD_CODE_OK) {
		ERROR("Bad return code on TONE_END (%02x)\n",
		      resp.code);
		ret = -99;
		goto done;
	}

done:
	free(data);

	return ret;
}


/* Driver API */

static void shinkos1245_cmdline(void)
{
	DEBUG("\t\t[ -m ]           # Query media\n");
	DEBUG("\t\t[ -s ]           # Query status\n");
	DEBUG("\t\t[ -u ]           # Query user string\n");
	DEBUG("\t\t[ -U sometext ]  # Set user string\n");
	DEBUG("\t\t[ -R ]           # Reset printer\n");
	DEBUG("\t\t[ -X jobid ]     # Abort a printjob\n");
	DEBUG("\t\t[ -F ]           # Tone curve refers to FINE mode\n");
	DEBUG("\t\t[ -c filename ]  # Get user/NV tone curve\n");
	DEBUG("\t\t[ -C filename ]  # Set user/NV tone curve\n");
	DEBUG("\t\t[ -l filename ]  # Get current tone curve\n");
	DEBUG("\t\t[ -L filename ]  # Set current tone curve\n");
}

int shinkos1245_cmdline_arg(void *vctx, int argc, char **argv)
{
	struct shinkos1245_ctx *ctx = vctx;
	int i, j = 0;

	if (!ctx)
		return -1;

	while ((i = getopt(argc, argv, GETOPT_LIST_GLOBAL "c:C:l:L:FmRsuU:X:")) >= 0) {
		switch(i) {
		GETOPT_PROCESS_GLOBAL
		case 'F':
			ctx->tonecurve = PARAM_TABLE_FINE;
			break;
		case 'c':
			j = get_tonecurve(ctx, TONE_TABLE_USER, ctx->tonecurve, optarg);
			break;
		case 'C':
			j = set_tonecurve(ctx, TONE_TABLE_USER, ctx->tonecurve, optarg);
			break;
		case 'l':
			j = get_tonecurve(ctx, TONE_TABLE_CURRENT, ctx->tonecurve, optarg);
			break;
		case 'L':
			j = set_tonecurve(ctx, TONE_TABLE_CURRENT, ctx->tonecurve, optarg);
			break;
		case 'm':
			j = shinkos1245_get_media(ctx);
			if (!j)
				shinkos1245_dump_media(ctx->medias, ctx->media_8x12, ctx->num_medias);
			break;
		case 'R':
			j = shinkos1245_reset(ctx);
			break;
		case 's': {
			struct shinkos1245_resp_status sts;
			j = shinkos1245_get_status(ctx, &sts);
			if (!j)
				shinkos1245_dump_status(ctx, &sts);
			break;
		}
		case 'u': {
			struct shinkos1245_resp_getid resp;
			j = shinkos1245_get_printerid(ctx, &resp);
			if (!j) {
				char buffer[sizeof(resp.data)+1];
				memcpy(buffer, resp.data, sizeof(resp.data));
				buffer[sizeof(resp.data)] = 0;
				INFO("Printer ID: %02x '%s'\n", resp.id, buffer);
			}
			break;
		}
		case 'U':
			j = shinkos1245_set_printerid(ctx, optarg);
			break;
		case 'X':
			j = shinkos1245_canceljob(ctx, atoi(optarg));
			break;
		default:
			break;  /* Ignore completely */
		}

		if (j) return j;
	}

	return 0;
}

static void *shinkos1245_init(void)
{
	struct shinkos1245_ctx *ctx = malloc(sizeof(struct shinkos1245_ctx));
	if (!ctx) {
		ERROR("Memory Allocation Failure!\n");
		return NULL;
	}
	memset(ctx, 0, sizeof(struct shinkos1245_ctx));

	ctx->tonecurve = PARAM_TABLE_STANDARD;

	return ctx;
}

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

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

	/* Ensure jobid is sane */
	ctx->jobid = jobid & 0x7f;
	if (!ctx->jobid)
		ctx->jobid++;

	if (test_mode < TEST_MODE_NOATTACH) {
		/* Query Media */
		if (shinkos1245_get_media(ctx))
			return CUPS_BACKEND_FAILED;
		if (!ctx->num_medias) {
			ERROR("Media Query Error\n");
			return CUPS_BACKEND_FAILED;
		}
	} else {
		int media_code = 1;
		if (getenv("MEDIA_CODE"))
			media_code = atoi(getenv("MEDIA_CODE"));

		ctx->media_8x12 = media_code;
		ctx->num_medias = 0;
	}
	ctx->marker.color = "#00FFFF#FF00FF#FFFF00";
	ctx->marker.name = ctx->media_8x12 ? "8x12" : "8x10";
	ctx->marker.levelmax = ctx->media_8x12 ? 230 : 280;
	ctx->marker.levelnow = -2;

	return CUPS_BACKEND_OK;
}

static void shinkos1245_cleanup_job(const void *vjob)
{
	const struct shinkos1245_printjob *job = vjob;

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

	free((void*)job);
}

static void shinkos1245_teardown(void *vctx) {
	struct shinkos1245_ctx *ctx = vctx;

	if (!ctx)
		return;

	free(ctx);
}

static int shinkos1245_read_parse(void *vctx, const void **vjob, int data_fd, int copies) {
	struct shinkos1245_ctx *ctx = vctx;
	int ret;
	uint8_t tmpbuf[4];

	struct shinkos1245_printjob *job = NULL;

	if (!ctx)
		return CUPS_BACKEND_FAILED;

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

	/* Read in then validate header */
	ret = read(data_fd, &ctx->hdr, sizeof(ctx->hdr));
	if (ret < 0) {
		shinkos1245_cleanup_job(job);
		return ret;
	}
	if (ret != sizeof(ctx->hdr)) {
		shinkos1245_cleanup_job(job);
		return CUPS_BACKEND_CANCEL;
	}

	if (le32_to_cpu(ctx->hdr.len1) != 0x10 ||
	    le32_to_cpu(ctx->hdr.len2) != 0x64 ||
	    le32_to_cpu(ctx->hdr.dpi) != 300) {
		ERROR("Unrecognized header data format!\n");
		shinkos1245_cleanup_job(job);
		return CUPS_BACKEND_CANCEL;
	}

	ctx->hdr.model = le32_to_cpu(ctx->hdr.model);

	if(ctx->hdr.model != 1245) {
		ERROR("Unrecognized printer (%u)!\n", ctx->hdr.model);
		shinkos1245_cleanup_job(job);
		return CUPS_BACKEND_CANCEL;
	}

	/* Finish byteswapping */
	ctx->hdr.media = le32_to_cpu(ctx->hdr.media);
	ctx->hdr.method = le32_to_cpu(ctx->hdr.method);
	ctx->hdr.mode = le32_to_cpu(ctx->hdr.mode);
	ctx->hdr.mattedepth = le32_to_cpu(ctx->hdr.mattedepth);
	ctx->hdr.dust = le32_to_cpu(ctx->hdr.dust);
	ctx->hdr.columns = le32_to_cpu(ctx->hdr.columns);
	ctx->hdr.rows = le32_to_cpu(ctx->hdr.rows);
	ctx->hdr.copies = le32_to_cpu(ctx->hdr.copies);

	/* Allocate space */
	job->datalen = ctx->hdr.rows * ctx->hdr.columns * 3;
	job->databuf = malloc(job->datalen);
	if (!job->databuf) {
		ERROR("Memory allocation failure!\n");
		shinkos1245_cleanup_job(job);
		return CUPS_BACKEND_RETRY_CURRENT;
	}

	{
		int remain = job->datalen;
		uint8_t *ptr = job->databuf;
		do {
			ret = read(data_fd, ptr, remain);
			if (ret < 0) {
				ERROR("Read failed (%d/%d/%d)\n",
				      ret, remain, job->datalen);
				perror("ERROR: Read failed");
				shinkos1245_cleanup_job(job);
				return ret;
			}
			ptr += ret;
			remain -= ret;
		} while (remain);
	}

	/* Make sure footer is sane too */
	ret = read(data_fd, tmpbuf, 4);
	if (ret != 4) {
		ERROR("Read failed (%d/%d/%d)\n",
		      ret, 4, 4);
		perror("ERROR: Read failed");
		shinkos1245_cleanup_job(job);
		return ret;
	}
	if (tmpbuf[0] != 0x04 ||
	    tmpbuf[1] != 0x03 ||
	    tmpbuf[2] != 0x02 ||
	    tmpbuf[3] != 0x01) {
		ERROR("Unrecognized footer data format!\n");
		shinkos1245_cleanup_job(job);
		return CUPS_BACKEND_FAILED;
	}

	*vjob = job;
	return CUPS_BACKEND_OK;
}

static int shinkos1245_main_loop(void *vctx, const void *vjob) {
	struct shinkos1245_ctx *ctx = vctx;
	int i, num, last_state = -1, state = S_IDLE;
	struct shinkos1245_resp_status status1, status2;

	const struct shinkos1245_printjob *job = vjob;

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

	copies = job->copies;

	/* Make sure print size is supported */
	for (i = 0 ; i < ctx->num_medias ; i++) {
		if (ctx->hdr.media == ctx->medias[i].code &&
		    ctx->hdr.method == ctx->medias[i].print_type &&
		    ctx->hdr.rows == ctx->medias[i].rows &&
		    ctx->hdr.columns == ctx->medias[i].columns)
			break;
	}
	if (i == ctx->num_medias) {
		ERROR("Unsupported print type\n");
		return CUPS_BACKEND_HOLD;
	}

	/* Fix max print count. */
	if (copies > 9999) // XXX test against remaining media?
		copies = 9999;

top:
	if (state != last_state) {
		if (dyesub_debug)
			DEBUG("last_state %d new %d\n", last_state, state);
	}

	/* Send status query */
	i = shinkos1245_get_status(ctx, &status1);
	if (i < 0)
		return CUPS_BACKEND_FAILED;

	if (memcmp(&status1, &status2, sizeof(status1))) {
		memcpy(&status2, &status1, sizeof(status1));
		// status changed.
	} else if (state == last_state) {
		sleep(1);
		goto top;
	}

	/* Make sure we're not in an error state */
	if (status1.state.status1 == STATE_STATUS1_ERROR)
		goto printer_error;

	last_state = state;

	fflush(stderr);

	switch (state) {
	case S_IDLE:
		if (status1.state.status1 == STATE_STATUS1_STANDBY) {
			state = S_PRINTER_READY_CMD;
			break;
		}

		if (status1.print_status == STATUS_IDLE) {
			state = S_PRINTER_READY_CMD;
			break;
		}
#if 0 // XXX is this necessary
		if (status1.state.status1 == STATE_STATUS1_WAIT) {
			INFO("Printer busy: %s\n",
			     shinkos1245_status_str(&status1));
			break;
		}
#endif
		/* If the printer is "busy" check to see if there's any
		   open memory banks so we can queue the next print */

		/* make sure we're not colliding with an existing
		   jobid */
		while (ctx->jobid == status1.counters2.bank1_id ||
		       ctx->jobid == status1.counters2.bank2_id) {
			ctx->jobid++;
			ctx->jobid &= 0x7f;
			if (!ctx->jobid)
				ctx->jobid++;
		}

		if (!status1.counters2.bank1_remain ||
		    !status1.counters2.bank2_remain) {
			state = S_PRINTER_READY_CMD;
			break;
		}
		break;
	case S_PRINTER_READY_CMD: {
		struct shinkos1245_cmd_print cmd;

		/* Set matte intensity */
		if (ctx->hdr.mattedepth != 0x7fffffff) {
			int current = -1;
			i = shinkos1245_get_matte(ctx, &current);
			if (i < 0)
				goto printer_error;
			if (current != ctx->hdr.mattedepth) {
				i = shinkos1245_set_matte(ctx, ctx->hdr.mattedepth);
				if (i < 0)
					goto printer_error;
				if (i > 0) {
					INFO("Can't set matte intensity when printing in progress...\n");
					state = S_IDLE;
					sleep(1);
					break;
				}
			}
		}

		INFO("Sending print job (internal id %u)\n", ctx->jobid);

		shinkos1245_fill_hdr(&cmd.hdr);
		cmd.cmd[0] = 0x0a;
		cmd.cmd[1] = 0x00;

		cmd.id = ctx->jobid;
		cmd.count = cpu_to_be16(uint16_to_packed_bcd(copies));
		cmd.columns = cpu_to_be16(ctx->hdr.columns);
		cmd.rows = cpu_to_be16(ctx->hdr.rows);
		cmd.media = ctx->hdr.media;
		cmd.mode = (ctx->hdr.mode & 0x3f) || ((ctx->hdr.dust & 0x3) << 6);
		cmd.combo = ctx->hdr.method;

		/* Issue print command */
		i = shinkos1245_do_cmd(ctx, &cmd, sizeof(cmd),
				       &status1, sizeof(status1),
				       &num);
		if (i < 0)
			goto printer_error;

		/* Check for buffer full state, and wait if we're full */
		if (status1.code != CMD_CODE_OK) {
			if (status1.print_status == STATUS_PRINTING) {
				sleep(1);
				break;
			} else {
				goto printer_error;
			}
		}

		/* Check for error states */
		if (status1.state.status1 == STATE_STATUS1_ERROR)
			goto printer_error;

		/* Send over data */
		INFO("Sending image data to printer\n");
		if ((i = send_data(ctx->dev, ctx->endp_down,
				   job->databuf, job->datalen)))
			return CUPS_BACKEND_FAILED;

		INFO("Waiting for printer to acknowledge completion\n");
		sleep(1);
		state = S_PRINTER_SENT_DATA;
		break;
	}
	case S_PRINTER_SENT_DATA:
		if (fast_return) {
			INFO("Fast return mode enabled.\n");
			state = S_FINISHED;
		}
		/* Check for completion */
		if (status1.print_status == STATUS_IDLE)
			state = S_FINISHED;

		break;
	default:
		break;
	}

	if (state != S_FINISHED)
		goto top;

	INFO("Print complete\n");

	return CUPS_BACKEND_OK;

printer_error:
	/* Byteswap */
	status1.state.status2 = be32_to_cpu(status1.state.status2);

	ERROR("Printer Error: %s # %02x %08x %02x\n",
	      shinkos1245_status_str(&status1),
	      status1.state.status1, status1.state.status2, status1.state.error);

	return CUPS_BACKEND_FAILED;
}

static int shinkos1245_query_serno(struct libusb_device_handle *dev, uint8_t endp_up, uint8_t endp_down, char *buf, int buf_len)
{
	struct shinkos1245_resp_getid resp;
	int i;

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

	i = shinkos1245_get_printerid(&ctx, &resp);
	if (i < 0)
		return CUPS_BACKEND_FAILED;

	for (i = 0 ; i < (int) sizeof(resp.data) && i < buf_len; i++) {
		buf[i] = resp.data[i];
	}

	/* Ensure null-termination */
	if (i < buf_len)
		buf[i] = 0;
	else
		buf[buf_len-1] = 0;

	return CUPS_BACKEND_OK;
}

static int shinkos1245_query_markers(void *vctx, struct marker **markers, int *count)
{
	struct shinkos1245_ctx *ctx = vctx;
	struct shinkos1245_resp_status status;

	/* Query status */
	if (shinkos1245_get_status(ctx, &status))
		return CUPS_BACKEND_FAILED;

	ctx->marker.levelnow = ctx->marker.levelmax - be32_to_cpu(status.counters.media);

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

	return CUPS_BACKEND_OK;
}

/* Exported */
#define USB_VID_SHINKO       0x10CE
#define USB_PID_SHINKO_S1245 0x0007

static const char *shinkos1245_prefixes[] = {
	"shinko-chcs1245",
	// extra
	"sinfonia-chcs1245",
	// backwards-compatibility
	"shinkos1245",
	NULL
};

struct dyesub_backend shinkos1245_backend = {
	.name = "Shinko/Sinfonia CHC-S1245/E1",
	.version = "0.26",
	.uri_prefixes = shinkos1245_prefixes,
	.cmdline_usage = shinkos1245_cmdline,
	.cmdline_arg = shinkos1245_cmdline_arg,
	.init = shinkos1245_init,
	.attach = shinkos1245_attach,
	.teardown = shinkos1245_teardown,
	.cleanup_job = shinkos1245_cleanup_job,
	.read_parse = shinkos1245_read_parse,
	.main_loop = shinkos1245_main_loop,
	.query_serno = shinkos1245_query_serno,
	.query_markers = shinkos1245_query_markers,
	.devices = {
		{ USB_VID_SHINKO, USB_PID_SHINKO_S1245, P_SHINKO_S1245, NULL, "shinko-chcs1245"},
		{ 0, 0, 0, NULL, NULL}
	}
};

/* CHC-S1245 data format

  Spool file consists of an 116-byte header, followed by RGB-packed data,
  followed by a 4-byte footer.  Header appears to consist of a series of
  4-byte Little Endian words.

   10 00 00 00 MM MM 00 00  00 00 00 00 01 00 00 00  MM == Model (ie 1245d)
   64 00 00 00 00 00 00 00  TT 00 00 00 00 00 00 00  TT == Media Size (0x10 fixed)
   MM 00 00 00 PP 00 00 00  00 00 00 00 ZZ ZZ ZZ ZZ  MM = Print Method (aka cut control), PP = Default/Glossy/Matte (0x01/0x03/0x05), ZZ == matte intensity (0x7fffffff for glossy, else 0x00000000 +- 25 for matte)
   VV 00 00 00 WW WW 00 00  HH HH 00 00 XX XX 00 00  VV == dust; 0x00 default, 0x01 off, 0x02 on, XX == Copies
   00 00 00 00 00 00 00 00  00 00 00 00 ce ff ff ff
   00 00 00 00 ce ff ff ff  QQ QQ 00 00 ce ff ff ff  QQ == DPI, ie 300.
   00 00 00 00 ce ff ff ff  00 00 00 00 00 00 00 00
   00 00 00 00

   [[Packed RGB payload of WW*HH*3 bytes]]

   04 03 02 01  [[ footer ]]


*/