summaryrefslogtreecommitdiff
path: root/profile/printcal.c
blob: f9107eb32127cb92749f2241f3244edadbd7b183 (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

			

/* 
 * Argyll Color Correction System
 * Print Device calibration curve generator.
 *
 * Author: Graeme W. Gill
 * Date:   2008/3/3
 *
 * Copyright 1996-2008 Graeme W. Gill
 * All rights reserved.
 *
 * This material is licenced under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 :-
 * see the License.txt file for licencing details.
 */

/*
 * This program takes in the colorent wedge test chart
 * points, and creates a set of per channel correction curves.
 */

/*
 * TTBD:
 *		Allow auto max threshold to be scaled on command line ?
 *		ie. -m# set % to go below the default optimal maximum.
 */


/*
	Additive spaces are handled by inverting the device values internally.
	(Such a space should probably have ICX_INVERTED set as well, indicating
	 that the underlying device is actually subtractive.) 
 */

#undef DEBUG

#define verbo stdout

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <fcntl.h>
#include <string.h>
#include <time.h>
#include "copyright.h"
#include "aconfig.h"
#include "cgats.h"
#include "numlib.h"
#include "sort.h"
#include "rspl.h"
#include "xicc.h"
#include "plot.h"


#define RSPLFLAGS (0 /* | RSPL_2PASSSMTH | RSPL_EXTRAFIT2 */)

#define RSPLSMOOTH 2.0	/* RSPL Smoothness factor use on measured device points */

#define TCURVESMOOTH 1.0 /* RSPL smoothness factor for target aim points */

#define GRES 256		/* Rspl grid resolution */
#define SLOPE_NORM 70.0	/* Normalized delta E for below thresholds */
#define MIN_SLOPE_A 8.0	/* Criteria for Auto max, DE/dDev at max */
#define MIN_SLOPE_O 3.0	/* Criteria for Auto max, min DE/dDev below max */

#define CAL_RES 256		/* Resolution saved to .cal file */

#define PRES 256		/* Plotting resolution */

void usage(char *diag, ...) {
	int i;
	fprintf(stderr,"Create printer calibration, Version %s\n",ARGYLL_VERSION_STR);
	fprintf(stderr,"Author: Graeme W. Gill, licensed under the AGPL Version 3\n");
	if (diag != NULL) {
		va_list args;
		fprintf(stderr,"  Diagnostic: ");
		va_start(args, diag);
		vfprintf(stderr, diag, args);
		va_end(args);
		fprintf(stderr,"\n");
	}
	fprintf(stderr,"usage: %s [-options] [prevcal] inoutfile\n",error_program);
	fprintf(stderr," -v verbosity    Verbose mode\n");
	fprintf(stderr," -p              Plot graphs.\n");
	fprintf(stderr," -i              Initial calibration, set targets, create .cal\n");
	fprintf(stderr," -r              Re-calibrate against previous .cal and create new .cal\n");
	fprintf(stderr," -e              Verify against previous .cal\n");
	fprintf(stderr," -I              Create imitation target from .ti3 and null calibration\n");
	fprintf(stderr," -d              Go through the motions but don't write any files\n");
	fprintf(stderr," -s smoothing    Extra curve smoothing (default 1.0)\n");
	fprintf(stderr," -A manufacturer Set the manufacturer description string\n");
	fprintf(stderr," -M model        Set the model description string\n");
	fprintf(stderr," -D description  Set the profile Description string\n");
	fprintf(stderr," -C copyright    Set the copyright string\n");
	fprintf(stderr," -x# percent     Set initial maximum device %% target (override auto)\n");
	fprintf(stderr," -m# percent     Set initial dev target to %% of auto maximum\n");
	fprintf(stderr," -n# deltaE      Set initial white minimum deltaE target\n");
	fprintf(stderr," -t# percent     Set initial 50%% transfer curve percentage target\n");
	fprintf(stderr,"   # = c, r, 0	 First channel\n");
	fprintf(stderr,"       m, g, 1	 Second channel\n");
	fprintf(stderr,"       y, b, 2	 Third channel\n");
	fprintf(stderr,"       k,    3	 Fourth channel, etc.\n");
	fprintf(stderr," -a              Create an Adobe Photoshop .AMP file as well as a .cal\n");
	fprintf(stderr," prevcal         Base name of previous .cal file for recal or verify.\n");
	fprintf(stderr," inoutname       Base name of input .ti3 file, output .cal file\n");
	exit(1);
}

/* - - - - - - - - - - - - - - - - - - - - - - - */
typedef struct {
	double loc;					/* Location up the curve 0.0 - 1.0 */
	double val[MAX_CHAN];		/* Value at that location 0.0 - 1.0 */
} trans_point;

/* Class to hold a print calibration target */
struct _pcaltarg {
	inkmask devmask;            	/* ICX ink mask of device space */
	
	/* Note that with all of these, a value < 0.0 */
	/* indicates no value set. */
	int devmaxset;						/* Flag - nz if the devmax is set */
	double devmax[MAX_CHAN];			/* Device value maximum 0.0 - 1.0 */

	int ademaxset;						/* Flag - nz if the ademax is set */
	double ademax[MAX_CHAN];			/* abs DE maximum for each channel */

	int ademinset;						/* Flag - nz if the ademin is set */
	double ademin[MAX_CHAN];			/* abs DE minimum for each channel */

	int no_tpoints;						/* Number of transfer curve points */
	trans_point *tpoints;				/* Array of transfer curve points */

	char err[500];						/* Error message from diagnostics */

	/* Methods */
	void (*del)(struct _pcaltarg *p);

	/* Save/restore to a CGATS file */
	int (*write)(struct _pcaltarg *p, cgats *cg, int tab);	/* return nz on error */
	int (*read)(struct _pcaltarg *p, cgats *cg, int tab);	/* return nz on error */

	/* Set values in the target */
	void (*update_devmax)(struct _pcaltarg *p, int chan, double val);
	void (*update_ademax)(struct _pcaltarg *p, int chan, double val);
	void (*update_ademin)(struct _pcaltarg *p, int chan, double val);
	void (*update_tcurve)(struct _pcaltarg *p, int chan, double loc, double val);

	/* Reurn nz if the target has been set */
	int (*is_set)(struct _pcaltarg *p);

	/* Update settings or from one from another */
	void (*update)(struct _pcaltarg *p, struct _pcaltarg *s);

}; typedef struct _pcaltarg pcaltarg; 

static void pcaltarg_del(pcaltarg *p) {
	if (p != NULL) {
		free(p);
	}
}

/* Write the cal target to a givent cgats table */
static int pcaltarg_write(pcaltarg *p, cgats *cg, int tab) {
	int i, j;
	time_t clk = time(0);
	struct tm *tsp = localtime(&clk);
	char *atm = asctime(tsp); /* Ascii time */
	char *ident = icx_inkmask2char(p->devmask, 1); 
	char *bident = icx_inkmask2char(p->devmask, 0); 
	int devchan = icx_noofinks(p->devmask);
	int nsetel = 0;
	cgats_set_elem *setel;	/* Array of set value elements */
	char buf[100];

	atm[strlen(atm)-1] = '\000';	/* Remove \n from end */

	/* Setup output cgats file */
	cg->add_table(cg, tt_other, 0);   /* Add a table for Calibration TarGet values */
	cg->add_kword(cg, tab, "DESCRIPTOR", "Argyll Calibration Target Definition File",NULL);
	cg->add_kword(cg, tab, "ORIGINATOR", "Argyll printcal", NULL);
	cg->add_kword(cg, tab, "CREATED",atm, NULL);
	cg->add_kword(cg, tab, "COLOR_REP", ident, NULL);

	/* Setup the table, which holds all the model parameters. */
	/* There is always a parameter per X Y Z or spectral band */
	cg->add_field(cg, tab, "PARAMTYPE", nqcs_t);
	nsetel++;
	sprintf(buf, "%s_I",bident);
	cg->add_field(cg, tab, buf, r_t);
	nsetel++;
	for (i = 0; i < devchan; i++) {
		inkmask imask = icx_index2ink(p->devmask, i);
		sprintf(buf, "%s_%s",bident,icx_ink2char(imask));
		cg->add_field(cg, tab, buf, r_t);
		nsetel++;
	}

	if ((setel = (cgats_set_elem *)malloc(sizeof(cgats_set_elem) * nsetel)) == NULL) {
		free(ident);
		free(bident);
		sprintf(p->err,"ctg_write: malloc of setel failed");
		return 1;
	}

	/* Write out the values */
	if (p->devmaxset) {
		/* This is informational only */
		setel[0].c = "DEVMAX_USED";
		setel[1].d = 0.0;		/* Not used */
			
		if (p->devmask & ICX_ADDITIVE) {
			for (i = 0; i < devchan; i++)
				setel[2+i].d = 1.0 - p->devmax[i];
		} else {
			for (i = 0; i < devchan; i++)
				setel[2+i].d = p->devmax[i];
		}
		cg->add_setarr(cg, tab, setel);
	}
	if (p->ademaxset) {
		setel[0].c = "DELMAX_AIM";
		setel[1].d = 0.0;		/* Not used */
			
		for (i = 0; i < devchan; i++)
			setel[2+i].d = p->ademax[i];
		cg->add_setarr(cg, tab, setel);
	}
	if (p->ademinset) {
		setel[0].c = "DELMIN_AIM";
		setel[1].d = 0.0;		/* Not used */
			
		for (i = 0; i < devchan; i++)
			setel[2+i].d = p->ademin[i];
		cg->add_setarr(cg, tab, setel);
	}
	for (j = 0; j < p->no_tpoints; j++) {
		setel[0].c = "TRANS_PNT";
		setel[1].d = p->tpoints[j].loc;

		for (i = 0; i < devchan; i++)
			setel[2+i].d = p->tpoints[j].val[i];
		cg->add_setarr(cg, tab, setel);
	}
	free(setel);
	free(ident);
	free(bident);

	return 0;
}

/* Read the cal target from a given cgats table */
static int pcaltarg_read(pcaltarg *p, cgats *cg, int tab) {
	char *bident;
	int devchan;
	int i, j, ix;
	int ti;					/* Temporary CGATs index */
	int spi[2+MAX_CHAN];	/* CGATS indexes for each field */
	char buf[100];

	if ((ti = cg->find_kword(cg, tab, "COLOR_REP")) < 0) {
		sprintf(p->err, "ctg_read: Can't fint COLOR_REP");
		return 1;
	}

	if ((p->devmask = icx_char2inkmask(cg->t[tab].kdata[ti]) ) == 0) {
		sprintf(p->err, "ctg_read: unrecognized COLOR_REP '%s'",cg->t[tab].kdata[ti]);
		return 1;
	}
	devchan = icx_noofinks(p->devmask);
	bident = icx_inkmask2char(p->devmask, 0); 

	/* Figure out the indexes of all the fields */
	if ((spi[0] = cg->find_field(cg, tab, "PARAMTYPE")) < 0) {
		sprintf(p->err, "ctg_read: Can't find field PARAMTYPE");
		free(bident);
		return 1;
	}
	sprintf(buf, "%s_I",bident);
	if ((spi[1] = cg->find_field(cg, tab, buf)) < 0) {
		sprintf(p->err, "ctg_read: Can't find field %s",buf);
		free(bident);
		return 1;
	}
	for (i = 0; i < devchan; i++) {
		inkmask imask = icx_index2ink(p->devmask, i);
		sprintf(buf, "%s_%s",bident,icx_ink2char(imask));
		if ((spi[2+i] = cg->find_field(cg, tab, buf)) < 0) {
			sprintf(p->err, "ctg_read: Can't find field %s",buf);
			free(bident);
			return 1;
		}
	}

	/* Go through all the entries in the table, putting them in the right place */
	for (ix = 0; ix < cg->t[tab].nsets; ix++) {

		if (strcmp((char *)cg->t[tab].fdata[ix][spi[0]], "DELMAX_AIM") == 0) { 
			for (i = 0; i < devchan; i++)
				p->ademax[i] = *((double *)cg->t[tab].fdata[ix][spi[2+i]]);
			p->ademaxset = 1;

		} else if (strcmp((char *)cg->t[tab].fdata[ix][spi[0]], "DELMIN_AIM") == 0) { 
			for (i = 0; i < devchan; i++)
				p->ademin[i] = *((double *)cg->t[tab].fdata[ix][spi[2+i]]);
			p->ademinset = 1;

		} else if (strcmp((char *)cg->t[tab].fdata[ix][spi[0]], "TRANS_PNT") == 0) { 
			if ((p->tpoints = (trans_point *)realloc(p->tpoints, sizeof(trans_point)
			                                                   * (p->no_tpoints+1))) == NULL)
				error("Realloc of tpoints");
			p->tpoints[p->no_tpoints].loc = *((double *)cg->t[tab].fdata[ix][spi[1]]);
			for (i = 0; i < devchan; i++)
				p->tpoints[p->no_tpoints].val[i] = *((double *)cg->t[tab].fdata[ix][spi[2+i]]);
			p->no_tpoints++;
		}
	}
	free(bident);

	return 0;
}

/* Update an individual setting. Use chan < 0 to set all to default */
void pcaltarg_update_devmax(struct _pcaltarg *p, int chan, double val) {
	int i;
	if (p->devmaxset == 0) {
		for (i = 0; i < MAX_CHAN; i++)
			p->devmax[i] = -1.0;
		p->devmaxset = 1;
	}
	if (chan >= 0)
		p->devmax[chan] = val;
}
void pcaltarg_update_ademax(struct _pcaltarg *p, int chan, double val) {
	int i;
	if (p->ademaxset == 0) {
		for (i = 0; i < MAX_CHAN; i++)
			p->ademax[i] = -1.0;
		p->ademaxset = 1;
	}
	if (chan >= 0)
		p->ademax[chan] = val;
}
void pcaltarg_update_ademin(struct _pcaltarg *p, int chan, double val) {
	int i;
	if (p->ademinset == 0) {
		for (i = 0; i < MAX_CHAN; i++)
			p->ademin[i] = -1.0;
		p->ademinset = 1;
	}
	if (chan >= 0)
		p->ademin[chan] = val;
}
void pcaltarg_update_tcurve(struct _pcaltarg *p, int chan, double loc, double val) {
	int i, j;

	/* See if a transfer curve point already exists */
	for (j = 0; j < p->no_tpoints; j++) {
		if (p->tpoints[j].loc == loc)
			break;
	}
	/* If not, allocate a new one */
	if (j >= p->no_tpoints) {
		p->no_tpoints++;
		if ((p->tpoints = (trans_point *)realloc(p->tpoints, sizeof(trans_point) * p->no_tpoints)) == NULL)
			error("Realloc of tpoints");
		p->tpoints[j].loc = loc;
		for (i = 0; i < MAX_CHAN; i++)
			p->tpoints[j].val[i] = -1.0;
	}
	p->tpoints[j].val[chan] = val;

	if (p->no_tpoints > 0) {
		/* Sort the transfer points into loc order */
#define HEAP_COMPARE(A,B) ((A).loc < (B).loc)
		HEAPSORT(trans_point, p->tpoints, p->no_tpoints);
#undef HEAP_COMPARE
	}
}

/* Reurn nz if the target has been set */
static int pcaltarg_is_set(pcaltarg *p) {
	if (p->devmaxset != 0
	 || p->ademaxset != 0
	 || p->ademinset != 0
	 || p->no_tpoints > 0)
		return 1;
	return 0;
}

/* Update one from another */
static void pcaltarg_update(pcaltarg *p, pcaltarg *s) {
	int i, j, k;

	if (s->devmaxset) {
		if (p->devmaxset == 0) {
			for (i = 0; i < MAX_CHAN; i++)
				p->devmax[i] = -1.0;
			p->devmaxset = 1;
		}
		for (i = 0; i < MAX_CHAN; i++) {
			if (s->devmax[i] >= 0.0)
				p->devmax[i] = s->devmax[i];
		}
	}

	if (s->ademaxset) {
		if (p->ademaxset == 0) {
			for (i = 0; i < MAX_CHAN; i++)
				p->ademax[i] = -1.0;
			p->ademaxset = 1;
		}
		for (i = 0; i < MAX_CHAN; i++) {
			if (s->ademax[i] >= 0.0)
				p->ademax[i] = s->ademax[i];
		}
	}

	if (s->ademinset) {
		if (p->ademinset == 0) {
			for (i = 0; i < MAX_CHAN; i++)
				p->ademin[i] = -1.0;
			p->ademinset = 1;
		}
		for (i = 0; i < MAX_CHAN; i++) {
			if (s->ademin[i] >= 0.0)
				p->ademin[i] = s->ademin[i];
		}
	}

	/* For each source transfer curve point */
	for (k = 0; k < s->no_tpoints; k++) {

		/* See if a transfer curve point already exists */
		for (j = 0; j < p->no_tpoints; j++) {
			if (p->tpoints[j].loc == s->tpoints[k].loc)
				break;
		}
		/* If not, allocate a new one */
		if (j >= p->no_tpoints) {
			p->no_tpoints++;
			if ((p->tpoints = (trans_point *)realloc(p->tpoints, sizeof(trans_point) * p->no_tpoints)) == NULL)
				error("Realloc of tpoints");
			p->tpoints[j].loc = s->tpoints[k].loc;
			for (i = 0; i < MAX_CHAN; i++)
				p->tpoints[j].val[i] = -1.0;
		}
		for (i = 0; i < MAX_CHAN; i++) {
			if (s->tpoints[k].val[i] >= 0.0)
				p->tpoints[j].val[i] = s->tpoints[k].val[i]; 
		}
	}
	if (s->no_tpoints > 0) {
		/* Sort the transfer points into loc order */
#define HEAP_COMPARE(A,B) ((A).loc < (B).loc)
		HEAPSORT(trans_point, p->tpoints, p->no_tpoints);
#undef HEAP_COMPARE
	}
}

/* Create a new, empty pcaltarget */
/* Return NULL on error */
pcaltarg *new_pcaltarg() {
	pcaltarg *p;

	if ((p = (pcaltarg *)calloc(1, sizeof(pcaltarg))) == NULL) {
		return NULL;
	}

	/* Set method pointers */
	p->del = pcaltarg_del;
	p->write = pcaltarg_write;
	p->read = pcaltarg_read;
	p->update_devmax = pcaltarg_update_devmax;
	p->update_ademax = pcaltarg_update_ademax;
	p->update_ademin = pcaltarg_update_ademin;
	p->update_tcurve = pcaltarg_update_tcurve;
	p->is_set = pcaltarg_is_set;
	p->update = pcaltarg_update;

	return p;
}

/* - - - - - - - - - - - - - - - - - - - - - - - */

/* A wedge sample value */
typedef struct {
	double inv;			/* Input value (cal table) */
	double dev;			/* Device value */
	double XYZ[3];		/* XYZ value */
	double Lab[3];		/* Lab value */
	double del;			/* Absolute delta (to white) */
} wval;

#define MAX_INVSOLN	10	/* Rspl maximum reverse solutions */

/* rspl setting functions */
static void rsplset1(void *cbntx, double *out, double *in) {
	co *dpoints = (co *)cbntx;
	int ix;

	ix = *((int*)&in[-0-1]);	/* Get grid index being looked up */
	out[0] = dpoints[ix].v[0];
}

/* Do an inverse lookup of an rspl. Return -1.0 on error. */
/* dir is value to favour if there are multiple solutions. */
static double rspl_ilookup(rspl *r, double dir, double in) {
	int nsoln;				/* Number of solutions found */
	co pp[MAX_INVSOLN];		/* Room for all the solutions found */
	int k;					/* Chosen solution */

	pp[0].v[0] = in;

	nsoln = r->rev_interp (
		r,				 	/* this */
		RSPL_NEARCLIP,		/* Clip to nearest (faster than vector) */
		MAX_INVSOLN,		/* Maximum number of solutions allowed for */
		NULL, 				/* No auxiliary input targets */
		NULL,				/* Clip vector direction and length */
		pp);				/* Input and output values */

	nsoln &= RSPL_NOSOLNS;		/* Get number of solutions */

	if (nsoln == 1) { /* Exactly one solution */
		k = 0;
	} else if (nsoln == 0) {	/* Zero solutions. This is unexpected. */
		return -1.0;
	} else {		/* Multiple solutions */
		double bdist = 1e300;
		int bsoln = 0;
//		warning("Multiple solutions for curve %d for DE %f",j,pp[0].v[0]); 
		for (k = 0; k < nsoln; k++) {
			double tt;
			tt = pp[k].p[0] - dir;
			tt *= tt;
			if (tt < bdist) {	/* Better solution */
				bdist = tt;
				bsoln = k;
			}
		}
		k = bsoln;
	}
	return pp[k].p[0];
}

int main(int argc, char *argv[]) {
	int fa,nfa,mfa;				/* current argument we're looking at */
	int verb = 0;
	int doplot = 0;
	int initial = 0;			/* Do initial creation of cal target and calibration */
	int recal = 0;				/* Do recalibrate/use cal target. */
	int verify = 0;				/* Do verification */
	int imitate = 0;			/* Do target directly from input */
	int dowrite = 1;			/* Write to files */
	int doamp = 0;				/* Write Adobe Photoshop .AMP file */
	profxinf xpi;				/* Extra profile/calibration information */
	pcaltarg *upct = NULL;		/* User settings of print calibration target */
	pcaltarg *pct = NULL;		/* Settings of print calibration target */
	double smooth = RSPLSMOOTH;	/* RSPL Smoothness factor */
	double xsmooth = 1.0;		/* Smoothing multiplier */
	double ver_maxde = 2.0;		/* Verify maximum Delta E (1.0 for smooth == 1.0) */
	int spec = 0;				/* Use spectral data flag */
	icxIllumeType illum = icxIT_D50;	/* Spectral defaults */
	xspect cust_illum;			/* Custom illumination spectrum */
	icxObserverType observ = icxOT_CIE_1931_2;	/* The classic observer */

	char baname[MAXNAMEL+1] = "";	/* Input & Output base name */
	char inname[MAXNAMEL+1] = "";	/* new .ti3 input file name */
	char calname[MAXNAMEL+1] = "";	/* previous .cal input file name */
	char outname[MAXNAMEL+1] = "";	/* new .cal output file name */
	char ampname[MAXNAMEL+1] = "";	/* new .amp output file name */
	double maxscale[MAX_CHAN];	/* Scale auto device maximum to % */
	cgats *icg = NULL;			/* .ti3 input cgats structure */
	int ti;						/* Temporary CGATs index */
	inkmask devmask;			/* ICX ink mask of device space */
	int devchan;				/* Number of chanels in device space */
	int isLab = 0;				/* Flag indicating whether PCS is XYZ or Lab */
	int n_pvals[MAX_CHAN];		/* Number of measurement values */
	wval *pvals[MAX_CHAN];		/* Patch measurement values */
	wval white;					/* Average white value */
	int n_white = 0;			/* Number of values to average */
	icmXYZNumber wht;			/* White value */
	rspl *raw[MAX_CHAN];		/* Raw Lab values fitted to rspl */
	rspl *ade[MAX_CHAN];		/* Absolute delta E */
	rspl *rde[MAX_CHAN];		/* Relative delta E */
	rspl *pcade[MAX_CHAN];		/* Previous calibrated absolute delta E */
	double mxade[MAX_CHAN];		/* Maximum ade value */
	double idpow[MAX_CHAN] = { -1.0 };		/* Ideal power-like of targen values */
	int n_cvals;				/* Number of calibration curve values */
	wval *cvals[MAX_CHAN];		/* Calibration curve tables */
	rspl *tcurves[MAX_CHAN];	/* Tweak target curves */

	int i, j;

	/* Init pointers to NULL */
	for (j = 0; j < MAX_CHAN; j++) {
		maxscale[j] = -1.0;
		pvals[j] = NULL;
		raw[j] = NULL;
		ade[j] = NULL;
		rde[j] = NULL;
		pcade[j] = NULL;
		cvals[j] = NULL;
		tcurves[j] = NULL;
	}

	error_program = argv[0];
	memset((void *)&xpi, 0, sizeof(profxinf));	/* Init extra profile info to defaults */
	if ((upct = new_pcaltarg()) == NULL || (pct = new_pcaltarg()) == NULL)
		error("new_caltarg failed");

	if (argc < 3)
		usage("Too few arguments, got %d expect at least %d",argc-1,2);

#ifdef NEVER
	{
		double src, dst, pp;

		src = 0.5;
		dst = 0.25;
		pp = icx_powlike_needed(src, dst); 
		printf("%f -> %f needs %f, check %f\n",src,dst,pp,icx_powlike(src,pp));
		
		src = 0.25;
		dst = 0.5;
		pp = icx_powlike_needed(src, dst); 
		printf("%f -> %f needs %f, check %f\n",src,dst,pp,icx_powlike(src,pp));

		src = 0.5;
		dst = 0.707106;
		pp = icx_powlike_needed(src, dst); 
		printf("%f -> %f needs %f, check %f\n",src,dst,pp,icx_powlike(src,pp));

		src = 0.5;
		dst = 0.5;
		pp = icx_powlike_needed(src, dst); 
		printf("%f -> %f needs %f, check %f\n",src,dst,pp,icx_powlike(src,pp));
	}
#endif // NEVER

	/* Process the arguments */
	mfa = 2;		/* Minimum final arguments */
	for(fa = 1;fa < argc;fa++) {

		nfa = fa;					/* skip to nfa if next argument is used */
		if (argv[fa][0] == '-') {	/* Look for any flags */
			char *na = NULL;		/* next argument after flag, null if none */

			if (argv[fa][2] != '\000')
				na = &argv[fa][2];		/* next is directly after flag */
			else {
				if ((fa+1+mfa) < argc) {
					if (argv[fa+1][0] != '-') {
						nfa = fa + 1;
						na = argv[nfa];		/* next is seperate non-flag argument */
					}
				}
			}

			if (argv[fa][1] == '?')
				usage("Usage requested");

			else if (argv[fa][1] == 'v') {
				if (na != NULL) {
					fa = nfa;
					verb = atoi(na);
				} else
					verb = 1;
			}

			else if (argv[fa][1] == 'p') {
				if (na != NULL) {
					fa = nfa;
					doplot = atoi(na);
				} else
					doplot = 1;				/* Plot various graphs */
			}

			else if (argv[fa][1] == 'i') {
				initial = 1;			/* Initial calibration */
				recal = 0;
				verify = 0;
				imitate = 0;
			}

			else if (argv[fa][1] == 'r') {
				initial = 0;
				recal = 1;			/* Recalibrate */
				verify = 0;
				imitate = 0;
			}

			else if (argv[fa][1] == 'e') {
				initial = 0;
				recal = 0;
				verify = 1;			/* Verify */
				imitate = 0;
			}

			else if (argv[fa][1] == 'I') {
				initial = 0;
				recal = 0;
				verify = 0;
				imitate = 1;			/* Imitation target */
			}

			else if (argv[fa][1] == 'd')
				dowrite = 0;			/* Don't write to files */

			else if (argv[fa][1] == 'a')
				doamp = 1;			/* write AMP file */

			/* Smoothing modfider */
			else if (argv[fa][1] == 's') {
				fa = nfa;
				if (na == NULL) usage("Expect argument to smoothing flag -s");
				xsmooth = atof(na);
			}

			/* Manufacturer description string */
			else if (argv[fa][1] == 'A') {
				fa = nfa;
				if (na == NULL) usage("Expect argument to manufacturer description flag -A");
				xpi.deviceMfgDesc = na;
			}

			/* Model description string */
			else if (argv[fa][1] == 'M') {
				fa = nfa;
				if (na == NULL) usage("Expect argument to model description flag -M");
				xpi.modelDesc = na;
			}

			/* Profile Description */
			else if (argv[fa][1] == 'D') {
				fa = nfa;
				if (na == NULL) usage("Expect argument to profile description flag -D");
				xpi.profDesc = na;
			}

			/* Copyright string */
			else if (argv[fa][1] == 'C') {
				fa = nfa;
				if (na == NULL) usage("Expect argument to copyright flag -C");
				xpi.copyright = na;
			}

			/* Per channel target modifiers */
			else if (argv[fa][1] == 'x'
			      || argv[fa][1] == 'm'
			      || argv[fa][1] == 'n' 
			      || argv[fa][1] == 't') {
				char fch = argv[fa][1];
				int chan = -1;
				double val = -1.0;
				fa = nfa;
				if (na == NULL)
					usage("Expect channel flag after flag -%c",argv[fa][1]);
    			switch (na[0]) {
					case 'c': case 'r': case '0':
						chan = 0;
						break;
					case 'm': case 'g': case '1':
						chan = 1;
						break;
					case 'y': case 'b': case '2':
						chan = 2;
						break;
					case 'k': case '3':
						chan = 3;
						break;
					case '4':
						chan = 4;
						break;
					case '5':
						chan = 5;
						break;
					case '6':
						chan = 6;
						break;
					case '7':
						chan = 7;
						break;
					case '8':
						chan = 8;
						break;
					case '9':
						chan = 9;
						break;
					case 'A':
						chan = 10;
						break;
					case 'B':
						chan = 11;
						break;
					case 'C':
						chan = 12;
						break;
					case 'D':
						chan = 13;
						break;
					case 'E':
						chan = 14;
						break;
					case 'F':
						chan = 15;
						break;
					default:
						usage("Unknown channel flag '%s' after flag -%c",argv[fa][2],argv[fa][1]);
				}
				++fa;
				if (fa >= argc || argv[fa][0] == '-') usage("Expect argument after flag -%c%c",fch,na[0]);
				val = atof(argv[fa]);
			
				if (fch == 'x') {
					if (val < 0.0 || val > 100.0)
						usage("Argument to -%c%c %f from '%s' is out of range",fch,na[0],val,argv[fa]);
					val /= 100.0;
					upct->update_devmax(upct, chan, val);

				} else if (fch == 'm') {
					if (val < 0.0 || val > 100.0)
						usage("Argument to -%c%c %f from '%s' is out of range",fch,na[0],val,argv[fa]);
					val /= 100.0;
					maxscale[chan] = val;

				} else if (fch == 'n') {
					upct->update_ademin(upct, chan, val);

				} else if (fch == 't') {
					if (val < 0.0 || val > 100.0)
						usage("Argument to -%c%c %f from '%s' is out of range",fch,na[0],val,argv[fa]);
					val /= 100.0;
					upct->update_tcurve(upct, chan, 0.5, val);
				}
			}
			else 
				usage("Unknown flag '%c'",argv[fa][1]);
		} else
			break;
	}

	smooth *= xsmooth;

	if (!(   (initial && !recal && !verify && !imitate)
	      || (!initial && recal && !verify && !imitate)
	      || (!initial && !recal && verify && !imitate)
	      || (!initial && !recal && !verify && imitate)))
		error("One of -i, -r -e or -I must be set");

	/* Get the file name arguments */
	if (verify || recal) {
		if (fa >= argc || argv[fa][0] == '-') usage("Missing prevoius .cal basename");
		strncpy(calname,argv[fa++],MAXNAMEL-4); calname[MAXNAMEL-4] = '\000';
		strcat(calname,".cal");
	}
	if (fa >= argc || argv[fa][0] == '-') usage("Missing .ti3 and new .cal basename");
	strncpy(baname,argv[fa++],MAXNAMEL-4); baname[MAXNAMEL-4] = '\000';
	strcpy(inname,baname);		/* new .ti3 file */
	strcat(inname,".ti3");
	strcpy(outname,baname);		/* New .cal file */
	strcat(outname,".cal");
	strcpy(ampname,baname);		/* New .amp file */
	strcat(ampname,".amp");

	if (fa < argc) usage("Too many arguments ('%s')",argv[fa]);

	/* Open and look at the .ti3 profile patches file */
	icg = new_cgats();				/* Create a CGATS structure */
	icg->add_other(icg, "CTI3"); 	/* our special input type is Calibration Target Information 3 */

	if (icg->read_name(icg, inname))
		error("CGATS file read error : %s",icg->err);

	if (icg->ntables == 0 || icg->t[0].tt != tt_other || icg->t[0].oi != 0)
		error ("Input file isn't a CTI3 format file");
	if (icg->ntables < 1)
		error ("Input file doesn't contain at least one table");

	/* See if CIE is actually available - some sources of .TI3 don't provide it */
	if (!spec
	 && icg->find_field(icg, 0, "LAB_L") < 0
	 && icg->find_field(icg, 0, "XYZ_X") < 0) {

		if (icg->find_kword(icg, 0, "SPECTRAL_BANDS") < 0)
			error ("Neither CIE nor spectral data found in file '%s'",inname);

		/* Switch to using spectral information */
		if (verb)
			printf("No CIE data found, switching to spectral with standard observer & D50\n");
		spec = 1;
		illum = icxIT_D50;
		observ = icxOT_CIE_1931_2;
	}
	
	/* If we requested spectral, check that it is available */
	if (spec) {
		if (icg->find_kword(icg, 0, "SPECTRAL_BANDS") < 0)
			error ("Requested spectral interpretation when data not available");
	}

	/* Get colorspace information from input CGATS file */
	{
		char *buf;
		char *inc, *outc;

		if ((ti = icg->find_kword(icg, 0, "COLOR_REP")) < 0)
			error("Input file doesn't contain keyword COLOR_REPS");

		if ((buf = strdup(icg->t[0].kdata[ti])) == NULL)
			error("Malloc failed - color rep");

		/* Split COLOR_REP into device and PCS space */
		inc = buf;
		if ((outc = strchr(buf, '_')) == NULL)
			error("COLOR_REP '%s' invalid", icg->t[0].kdata[ti]);
		*outc++ = '\000';

		if (strcmp(outc, "XYZ") == 0)
			isLab = 0;
		else if (strcmp(outc, "LAB") == 0)
			isLab = 1;
		else
			error("COLOR_REP '%s' invalid (Neither XYZ nor LAB)", icg->t[0].kdata[ti]);

		devmask = icx_char2inkmask(inc); 
		devchan = icx_noofinks(devmask);
		
		if (devchan == 0)
			error("COLOR_REP '%s' invalid (No matching devmask)", icg->t[0].kdata[ti]);
		
		if ((devmask & ICX_ADDITIVE) && !(devmask & ICX_INVERTED))
			warning("COLOR_REP '%s' is probably not suitable for print calibration!", icg->t[0].kdata[ti]);

		free(buf);
	}

	if (verify || recal || imitate) {
		if (upct->is_set(upct)) {
			warning("Command line calibration target paramers ignored on re-calibrate, verify and imitate!");
		}
	}

	/* For recalibrate or verify, load the previous calibration file */
	if (verify || recal) {
		cgats *tcg;						/* Previous .cal file */

		tcg = new_cgats();				/* Create a CGATS structure */
		tcg->add_other(tcg, "CAL"); 	/* our special input type is Calibration Target */

		if (tcg->read_name(tcg, calname))
			error("No cal target '%s' found for re-calibrate (%s)\n",calname,tcg->err);

		/* Check that this is an output cal file */
		if ((ti = tcg->find_kword(tcg, 0, "DEVICE_CLASS")) < 0)
			error ("Calibration file '%s'doesn't contain keyword DEVICE_CLASS",calname);
		if (strcmp(tcg->t[0].kdata[ti],"OUTPUT") != 0)
			error ("Calibration file '%s' doesn't has DEVICE_CLASS that is not OUTPUT",calname);

		if (pct->read(pct, tcg, 1) != 0)
			error("Reading cal target '%s' failed",calname);

		if (pct->devmask != devmask)
			error("Target '%s' colorspace '%s' doesn't match '%s' colorspace '%s'",
				   calname,icx_inkmask2char(pct->devmask, 1),inname,icx_inkmask2char(devmask, 1)); 

		/* Load the previous expected absolute DE response */
		/* It will be in the third table with other type "CAL" */
		if (tcg->ntables >= 3 && tcg->t[2].tt == tt_other && tcg->t[0].oi == 0) {
			int ti;
			char *bident;
			int spi[1+MAX_CHAN];	/* CGATS indexes for each field */
			char buf[100];

			bident = icx_inkmask2char(pct->devmask, 0); 

			if (tcg->t[2].nsets <= 0)
				error ("No Calibration Expected DE Response in '%s'",calname);

			/* Figure out the indexes of all the fields */
			sprintf(buf, "%s_I_DE",bident);
			if ((spi[0] = tcg->find_field(tcg, 2, buf)) < 0)
				error("Can't find field %s in '%s'",buf,calname);

			for (i = 0; i < devchan; i++) {
				inkmask imask = icx_index2ink(pct->devmask, i);
				sprintf(buf, "%s_%s_DE",bident,icx_ink2char(imask));
				if ((spi[1+i] = tcg->find_field(tcg, 2, buf)) < 0)
					error("Can't find field %s in '%s'",buf,calname);
			}

			/* Read in each channels values and put them in a rspl */
			for (j = 0; j < devchan; j++) {
				datai low,high;
				int gres[MXDI];
				co *dpoints;

				low[0] = 0.0;
				high[0] = 1.0;
				gres[0] = tcg->t[2].nsets;

				if ((pcade[j] = new_rspl(RSPL_NOFLAGS,1, 1)) == NULL)
					error("new_rspl() failed");

				if ((dpoints = malloc(sizeof(co) * gres[0])) == NULL)
					error("malloc dpoints[%d] failed",gres[0]);

				/* Copy the points to our array */
				if (devmask & ICX_ADDITIVE) {
					for (i = 0; i < gres[0]; i++) {
						dpoints[i].p[0] = 1.0 - i/(double)(gres[0]-1);
						dpoints[i].v[0] = *((double *)tcg->t[2].fdata[gres[0]-1-i][spi[1+j]]);
					}
				} else {
					for (i = 0; i < gres[0]; i++) {
						dpoints[i].p[0] = i/(double)(gres[0]-1);
						dpoints[i].v[0] = *((double *)tcg->t[2].fdata[i][spi[1+j]]);
					}
				}

				pcade[j]->set_rspl(pcade[j],
						   0, 
						   (void *)dpoints,		/* Read points */
						   rsplset1,			/* Setting function */
						   low, high, gres,		/* Low, high, resolution of grid */
						   NULL, NULL			/* Default data scale */
						   );
				free(dpoints);
			}
			free(bident);
		}
		tcg->del(tcg);

	} else {	/* Must be an initial or Imitation calibration */

		pct->devmask = devmask;

		/* Set the cal target from any user supplied parameters */
		pct->update(pct, upct);

		/* No previous absolute de reference */
		for (j = 0; j < devchan; j++)
			pcade[j] = NULL;
	}

	/* Common processing: */

	/* Read in the patch data */
	{
		char buf[100];
		char *pcsfname[2][3] = { { "XYZ_X", "XYZ_Y", "XYZ_Z" },
		                         { "LAB_L", "LAB_A", "LAB_B" } };
		int dvi[MAX_CHAN];	/* CGATS indexes for each device field */
		int pcsix[3];		/* XYZ/Lab chanel indexes */
		xsp2cie *sp2cie = NULL;		/* Spectral conversion object */
		xspect sp;
		int  spi[XSPECT_MAX_BANDS];	/* CGATS indexes for each wavelength */
		char *bident = icx_inkmask2char(devmask, 0); 
	
		/* Figure out the indexes of all the device fields */
		for (j = 0; j < devchan; j++) {
			inkmask imask = icx_index2ink(devmask, j);
			sprintf(buf, "%s_%s",bident,icx_ink2char(imask));
			if ((dvi[j] = icg->find_field(icg, 0, buf)) < 0)
				error("Can't find field %s in '%s'",buf,inname);
#ifdef DEBUG
			printf("devn chan %d field %s = %d\n",j,buf,dvi[j]);
#endif
		}
		free(bident);

		if (spec) {
			int ii;
			char buf[100];

			if ((ii = icg->find_kword(icg, 0, "SPECTRAL_BANDS")) < 0)
				error ("Input file doesn't contain keyword SPECTRAL_BANDS");
			sp.spec_n = atoi(icg->t[0].kdata[ii]);
			if ((ii = icg->find_kword(icg, 0, "SPECTRAL_START_NM")) < 0)
				error ("Input file doesn't contain keyword SPECTRAL_START_NM");
			sp.spec_wl_short = atof(icg->t[0].kdata[ii]);
			if ((ii = icg->find_kword(icg, 0, "SPECTRAL_END_NM")) < 0)
				error ("Input file doesn't contain keyword SPECTRAL_END_NM");
			sp.spec_wl_long = atof(icg->t[0].kdata[ii]);
			sp.norm = 100.0;

			/* Find the fields for spectral values */
			for (j = 0; j < sp.spec_n; j++) {
				int nm;
		
				/* Compute nearest integer wavelength */
				nm = (int)(sp.spec_wl_short + ((double)j/(sp.spec_n-1.0))
				            * (sp.spec_wl_long - sp.spec_wl_short) + 0.5);
				
				sprintf(buf,"SPEC_%03d",nm);

				if ((spi[j] = icg->find_field(icg, 0, buf)) < 0)
					error("Input file doesn't contain field %s",buf);
			}

			/* Create a spectral conversion object to XYZ */
			if ((sp2cie = new_xsp2cie(illum, &cust_illum, observ, NULL, icSigXYZData, icxClamp)) == NULL)
				error("Creation of spectral conversion object failed");

			/* To add FWA comp. would have to locate/create spectral white here, */
			/* then set the FWA comp. on. */
			/* See profout.c */

		} else {
			/* Figure out the indexes of the PCS fields */
			for (j = 0; j < 3; j++) {
				if ((i = icg->find_field(icg, 0, pcsfname[isLab][j])) >= 0) {
					if (icg->t[0].ftype[i] != r_t)
						error ("Field %s is wrong type",pcsfname[isLab][j]);
					pcsix[j] = i;
#ifdef DEBUG
					printf("PCS chan %d field %s = %d\n",j,pcsfname[isLab][j],pcsix[j]);
#endif
				} else {
					error ("Failed to find field %s",pcsfname[isLab][j]);
				}
			}
		}
	
		n_cvals = 0;
		for (j = 0; j < devchan; j++) {
			pvals[j] = NULL;
			n_pvals[j] = 0;
			cvals[j] = NULL;
		}

		/* Read all the test patches in */
		for (i = 0; i < icg->t[0].nsets; i++) {
			double maxv = -1.0;
			int maxch;

#ifdef DEBUG
			printf("Reading patch %d\n",i);
#endif

			/* Locate the maximum device value of any channel */
			for (j = 0; j < devchan; j++) {
				double val = *((double *)icg->t[0].fdata[i][dvi[j]]) / 100.0;
				if (devmask & ICX_ADDITIVE)
					val = 1.0 - val;
				if (val > maxv) {
					maxv = val;
					maxch = j;
				}
			}
#ifdef DEBUG
			printf("max %f at chan %d\n",maxv,maxch);
#endif
			/* Treat white specially, and take it out of the list */
			if (maxv < 1e-6) {
				double wxyz[3];
				if (n_white == 0) {
					white.dev = 0.0;
					for (j = 0; j < 3; j++)
						white.XYZ[j] = 0.0;
				}
				if (spec) {
					/* Read and convert the spectral value */
					for (j = 0; j < sp.spec_n; j++)
						sp.spec[j] = *((double *)icg->t[0].fdata[i][spi[j]]);

					sp2cie->convert(sp2cie, wxyz, &sp);

				} else {
					/* Read the CIE value */
					for (j = 0; j < 3; j++)
						wxyz[j] = *((double *)icg->t[0].fdata[i][pcsix[j]]);

					/* And convert to XYZ 0..1 */
					if (isLab) {
						icmLab2XYZ(&icmD50, wxyz, wxyz);
					} else {
						for (j = 0; j < 3; j++)
							wxyz[j] /= 100.0;
					}
				}
			
				white.dev += maxv;
				for (j = 0; j < 3; j++)
					white.XYZ[j] += wxyz[j];
				n_white++;
#ifdef DEBUG
				printf("  white: dev %f,XYZ %f %f %f\n",
				white.dev,white.XYZ[0]/n_white, white.XYZ[1]/n_white, white.XYZ[2]/n_white);
#endif
			} else {
				wval *vp;
				/* Check that all the non-max value channels are zero */
				for (j = 0; j < devchan; j++) {
					double val = *((double *)icg->t[0].fdata[i][dvi[j]]) / 100.0;
					if (devmask & ICX_ADDITIVE)
						val = 1.0 - val;
					if (j == maxch)
						continue;
					if (val > 0.001)
						break;
				}
				if (j < devchan) {
#ifdef DEBUG
				printf("Skipping patch\n");
#endif
					continue;		/* Ignore this patch */
				}

				if ((pvals[maxch] = (wval *)realloc(pvals[maxch],
				                       sizeof(wval) * (n_pvals[maxch]+1))) == NULL)
					error("Realloc of pvals failed");
				vp = &pvals[maxch][n_pvals[maxch]];
				vp->dev = maxv;

				if (spec) {
					/* Read and convert the spectral value */
					for (j = 0; j < sp.spec_n; j++)
						sp.spec[j] = *((double *)icg->t[0].fdata[i][spi[j]]);

					sp2cie->convert(sp2cie, vp->XYZ, &sp);

				} else {
					/* Read the CIE value */
					for (j = 0; j < 3; j++)
						vp->XYZ[j] = *((double *)icg->t[0].fdata[i][pcsix[j]]);

					/* And convert to XYZ 0..1 */
					if (isLab) {
						icmLab2XYZ(&icmD50, vp->XYZ, vp->XYZ);
					} else {
						for (j = 0; j < 3; j++)
							vp->XYZ[j] /= 100.0;
					}
				}
				/* Temporary D50 Lab */
				icmXYZ2Lab(&icmD50, vp->Lab, vp->XYZ);
#ifdef DEBUG
				printf("  patch %d: dev %f,XYZ %f %f %f, D50 Lab %f %f %f\n",
				n_pvals[maxch], vp->dev,vp->XYZ[0], vp->XYZ[1], vp->XYZ[2],
				vp->Lab[0], vp->Lab[1], vp->Lab[2]);
#endif
				n_pvals[maxch]++;
			}
		}

		/* Average the white */
		if (n_white == 0)
			error("Can't find even one white patch in '%s'",inname);
#ifdef DEBUG
			printf("% white patches\n",n_white);
#endif
		for (j = 0; j < 3; j++) {
			white.dev    /= (double)n_white;
			white.XYZ[j] /= (double)n_white;
		}
		icmAry2XYZ(wht, white.XYZ);
		icmXYZ2Lab(&icmD50, white.Lab, white.XYZ);

		/* Convert the Lab white reference to absolute */
		wht.X /= wht.Y;
		wht.Z /= wht.Y;
		wht.Y /= wht.Y;

		if (verb) {
			icmXYZ2Lab(&icmD50, white.Lab, white.XYZ);
			printf("Average white = XYZ %f %f %f, D50 Lab %f %f %f\n",
			white.XYZ[0], white.XYZ[1], white.XYZ[2], white.Lab[0], white.Lab[1], white.Lab[2]);
		}

		for (j = 0; j < devchan; j++) {
			wval *wp;

			/* Add averaged white back into each channel */
			if ((pvals[j] = (wval *)realloc(pvals[j],
			                       sizeof(wval) * (n_pvals[j]+1))) == NULL)
				error("Realloc (%d) of pvals failed",n_pvals[j]+1);
			wp = &pvals[j][n_pvals[j]];
			wp->dev = white.dev;
			wp->XYZ[0] = white.XYZ[0];
			wp->XYZ[1] = white.XYZ[1];
			wp->XYZ[2] = white.XYZ[2];
			n_pvals[j]++;

			/* Convert all the XYZ values to Lab paper relative */
			for (i = 0; i < n_pvals[j]; i++) {
				wp = &pvals[j][i];
				icmXYZ2Lab(&wht, wp->Lab, wp->XYZ);
			}

			/* Sort the channel acording to device value */ 
			/* For a consistent result for identical device values, */
			/* secondary sort by inverse CIE value */
//#define HEAP_COMPARE(A,B) ((A).dev < (B).dev)
#define HEAP_COMPARE(A,B) ((A).dev != (B).dev ? ((A).dev < (B).dev) : ((A).Lab[0] > (B).Lab[0])) 
			HEAPSORT(wval, pvals[j], n_pvals[j]);
#undef HEAP_COMPARE

			/* Check the maximum value looks OK */
			if (n_pvals[j] < 5)
				warning("Channel %d has only %d test patches",n_pvals[j]);
			if (pvals[j][n_pvals[j]-1].dev < 0.99)
				warning("Channel %d has max test patch value of %f",pvals[j][n_pvals[j]-1]); 

			if (verb > 1) {
				printf("Chan %d has %d raw values:\n",j,n_pvals[j]);
				for (i = 0; i < n_pvals[j]; i++) {
					wp = &pvals[j][i];
					printf("  %d: dev %f,XYZ %f %f %f, Lab %f %f %f\n",
					       i,wp->dev,wp->XYZ[0], wp->XYZ[1], wp->XYZ[2],
					         wp->Lab[0], wp->Lab[1], wp->Lab[2]);
				}
			}
		}

		if (sp2cie != NULL)
			sp2cie->del(sp2cie);
	}
	icg->del(icg);		/* Clean up */

	/* Interpolate Lab using rspl */
	for (j = 0; j < devchan; j++) {
		datai low,high;
		datao olow,ohigh;
		int gres[MXDI];
		double avgdev[MXDO];
		cow *dpoints;

		low[0] = 0.0;
		high[0] = 1.0;
		gres[0] = GRES;
		olow[0] = 0.0;
		ohigh[0] = 100.0;
		olow[1] = olow[2] = -128.0; 
		ohigh[1] = ohigh[2] = 128.0;
		avgdev[0] = 0.0025;
		avgdev[1] = 0.005;
		avgdev[2] = 0.005;

		if ((raw[j] = new_rspl(RSPL_NOFLAGS,1, 3)) == NULL)
			error("new_rspl() failed");

		if ((dpoints = (cow *)malloc(sizeof(cow) * n_pvals[j])) == NULL)
			error("malloc dpoints[%d] failed",n_pvals[j]);

		for (i = 0; i < n_pvals[j]; i++) {
			dpoints[i].p[0] = pvals[j][i].dev;
			dpoints[i].v[0] = pvals[j][i].Lab[0];
			dpoints[i].v[1] = pvals[j][i].Lab[1];
			dpoints[i].v[2] = pvals[j][i].Lab[2];
			if (i == 0)
				dpoints[i].w = (double)n_white;
			else
				dpoints[i].w = 1.0;
		}

		raw[j]->fit_rspl_w(raw[j],
		           RSPLFLAGS,
		           dpoints,			/* Test points */
		           n_pvals[j],			/* Number of test points */
		           low, high, gres,		/* Low, high, resolution of grid */
		           olow, ohigh,			/* Default data scale */
		           smooth,				/* Smoothing */
		           avgdev,				/* Average deviation */
		           NULL);				/* iwidth */


		if (verb > 1) {
		}

		free(dpoints);
	}

	/* Plot the raw curves */
	if (doplot > 1) {
		double xx[PRES];
		double yy[3][PRES];

		for (j = 0; j < devchan; j++) {
			printf("Chan %d raw L*a*b*:\n",j);
			for (i = 0; i < PRES; i++) {
				co tp;	/* Test point */
				xx[i] = i/(double)(PRES-1);
				tp.p[0] = xx[i];
				raw[j]->interp(raw[j], &tp);
				yy[0][i] = tp.v[0];
				yy[1][i] = tp.v[1];
				yy[2][i] = tp.v[2];
			}
			do_plot(xx, yy[0], yy[1], yy[2], PRES);
		}
	}

	/* Create a RSPL of absolute deltaE and relative deltaE '94 */ 
	for (j = 0; j < devchan; j++) {
		datai low,high;
		int gres[MXDI];
		double avgdev[MXDO];
		co *dpoints_a;
		co *dpoints_r;
		double wh[3], prev[3], tot;

		low[0] = 0.0;
		high[0] = 1.0;
		gres[0] = GRES;
		avgdev[0] = 0.0;

		if ((ade[j] = new_rspl(RSPL_NOFLAGS,1, 1)) == NULL)
			error("new_rspl() failed");
		if (imitate) {
			if ((pcade[j] = new_rspl(RSPL_NOFLAGS,1, 1)) == NULL)
				error("new_rspl() failed");
		}
		if ((rde[j] = new_rspl(RSPL_NOFLAGS,1, 1)) == NULL)
			error("new_rspl() failed");

		if ((dpoints_a = malloc(sizeof(co) * GRES)) == NULL)
			error("malloc dpoints[%d] failed",GRES);
		if ((dpoints_r = malloc(sizeof(co) * GRES)) == NULL)
			error("malloc dpoints[%d] failed",GRES);

//printf("~1 Chan %d:\n",j);
		for (i = 0; i < GRES; i++) {
			co tp;	/* Test point */

			tp.p[0] = i/(double)(GRES-1);
			raw[j]->interp(raw[j], &tp);

			dpoints_a[i].p[0] = tp.p[0];
			dpoints_r[i].p[0] = tp.p[0];
			if (i == 0) {
//printf("~1 wht = %f %f %f\n",tp.v[0],tp.v[1],tp.v[2]);
				tot = 0.0;
				prev[0] = wh[0] = tp.v[0];
				prev[1] = wh[1] = tp.v[1];
				prev[2] = wh[2] = tp.v[2];
				dpoints_a[i].v[0] = 0.0;
				dpoints_r[i].v[0] = 0.0;
			} else {
//printf("~1 samp %d = %f %f %f\n",i,tp.v[0],tp.v[1],tp.v[2]);
				/* Use Euclidean for large DE: (CIE94 stuffs up here) */
				dpoints_a[i].v[0] = icmLabDE(tp.v, wh);
				/* And CIE94 for small: */
				tot += icmCIE94(tp.v, prev);
				prev[0] = tp.v[0];
				prev[1] = tp.v[1];
				prev[2] = tp.v[2];
				dpoints_r[i].v[0] = tot;
			}
//printf("~1   %d: dev %f, ade %f, rde %f\n",i,tp.p[0],dpoints_a[i].v[0],dpoints_r[i].v[0]);
		}

		ade[j]->set_rspl(ade[j],
		           0, 
		           (void *)dpoints_a,	/* Test points */
		           rsplset1,			/* Setting function */
		           low, high, gres,		/* Low, high, resolution of grid */
		           NULL, NULL			/* Default data scale */
		           );
		if (imitate) {
			pcade[j]->set_rspl(pcade[j],
			           0, 
			           (void *)dpoints_a,	/* Test points */
			           rsplset1,			/* Setting function */
			           low, high, gres,		/* Low, high, resolution of grid */
			           NULL, NULL			/* Default data scale */
			           );
		}
		rde[j]->set_rspl(rde[j],
		           0, 
		           (void *)dpoints_r,		/* Test points */
		           rsplset1,			/* Setting function */
		           low, high, gres,		/* Low, high, resolution of grid */
		           NULL, NULL			/* Default data scale */
		           );
		free(dpoints_a);
		free(dpoints_r);
	}

	if (initial) {
		/* Establish the ademax values */
		pct->update_devmax(pct, -1, -1.0);		/* Make sure there is a value for each */
		pct->update_ademax(pct, -1, -1.0);
		pct->update_ademin(pct, -1, -1.0);
		for (j = 0; j < devchan; j++) {
			co tp;	/* Test point */

			if (pct->devmax[j] < 0.0) {		/* Auto */
				double maxd, maxde, maxix;
				/* Locate the point of maximum aDE */
				for (maxde = -1.0, i = 0; i < GRES; i++) {

					tp.p[0] = i/(GRES-1.0);
					ade[j]->interp(ade[j], &tp);
					if (tp.v[0] > maxde) {
						maxd = tp.p[0];
						maxde = tp.v[0];
						maxix = i;
					}
				}
				pct->devmax[j] = maxd;
				pct->ademax[j] = maxde;		/* Temporary */
//printf("Chan %d, dev %f, max de = %f\n", j, maxd, maxde);

				if (maxd < 0.2) {
					warning("Chan %d, max DE point %f is below < 0.2 - ignored\n", j, maxd);
					maxix = GRES-1;
				}
				/* Then locate the point below that where the slope */
				/* becomes reasonable. */ 
				for (i = maxix; i >= 40; i--) {
					double aslope, minslope = 1e6;
					double naslope, nminslope;
					int k;

					/* Compute the minimum over a span of 20/GRES */
					for (k = 0; k < 40; k++) {
						double dp, dv, slope;

						tp.p[0] = (i-k)/(GRES-1.0);
						dp = tp.p[0];
						ade[j]->interp(ade[j], &tp);
						dv = tp.v[0];

						tp.p[0] = (i-k-1)/(GRES-1.0);
						ade[j]->interp(ade[j], &tp);
						slope = (dv - tp.v[0])/(dp - (i-k-1)/(GRES-1.0));
						if (k == 0)
							aslope = slope;
//printf("  Chan %d, dev %f, dv = %f, slope = %f\n", j, (i-k)/(GRES-1.0),dv - tp.v[0],slope);
						if (slope < minslope)
							minslope = slope;
					}
//printf("Chan %d, dev %f, aslope = %f, min slope = %f\n", j, i/(GRES-1.0),aslope,minslope);
					/* Normalize the slopes */
					naslope = aslope * SLOPE_NORM/pct->ademax[j];
					nminslope = minslope * SLOPE_NORM/pct->ademax[j];
//printf("Chan %d, dev %f, norm aslope = %f, min slope = %f\n", j, i/(GRES-1.0),naslope,nminslope);

					if (naslope > MIN_SLOPE_A && nminslope >= MIN_SLOPE_O)
						break;
				}
				pct->devmax[j] = i/(GRES-1.0);

				/* Scale auto max device value */
				if (maxscale[j] >= 0.0)
					pct->devmax[j] *= maxscale[j];

			/* Manually set initial dev max */
			} else {
				if (maxscale[j] >= 0.0)
					warning("Chan %d, scale %.1f%% of auto max ignored since max override used\n", j, maxscale[j] * 100.0);
			}

			/* Lookup devmax to set ademax */
			tp.p[0] = pct->devmax[j];
			ade[j]->interp(ade[j], &tp);
			pct->ademax[j] = tp.v[0];

	
			/* Establish a default ademin value */
			if (pct->ademin[j] < 0.0)
				pct->ademin[j] = 0.0;
		}

	} else if (recal) {

		/* Since the plot markers use devmax, look it up */
		for (j = 0; j < devchan; j++) {
			if ((pct->devmax[j] = rspl_ilookup(ade[j], 0.5, pct->ademax[j])) < 0.0)
				error("Unexpected failure to invert curve %d for ADE %f",j,pct->ademax[j]); 
		}
	}

	/* Find the maximum aDE value for each curve */
	for (j = 0; j < devchan; j++) {
		co tp;	/* Test point */
		mxade[j] = -1e6;
		for (i = 0; i < PRES; i++) {
			tp.p[0] = i/(double)(PRES-1);
			ade[j]->interp(ade[j], &tp);
			if (tp.v[0] > mxade[j])
				mxade[j] = tp.v[0];
		}
	}

	if (initial || recal) {
		/* Compute an ideal power-like value for test target */
		for (j = 0; j < devchan; j++) {
			double hdv;			/* Half device value */
			double hdvrde;		/* Half device rDE value */
			double thdvrde;		/* Target half device rDE value */
			double thdv;		/* Target half device value */
			double fdvrde;		/* Full device rDE value */
			co tp;	/* Test point */
	
			/* full rDE */
			tp.p[0] = pct->devmax[j];
			rde[j]->interp(rde[j], &tp);
			fdvrde = tp.v[0];

			/* Half device value of maximum */
			hdv = pct->devmax[j] * 0.5;
	
			/* rDE value half the device value */
			tp.p[0] = hdv;
			rde[j]->interp(rde[j], &tp);
			hdvrde = tp.v[0];
	
			/* rDE value we'd like at half the device value */
			thdvrde = 0.5 * fdvrde;
			
			/* Device value to get the rDE value we'd like at half */
			if ((thdv = rspl_ilookup(rde[j], 0.5, thdvrde)) < 0.0)
				error("Unexpected failure to invert curve %d for ADE %f",j,thdvrde); 

//printf("hdv %f, hdvrde %f, thdvrde %f, fdvrde %f, thdv %f\n",hdv,hdvrde,thdvrde, fdvrde,thdv);
	
			/* Power like value needed to get rDE value we'd like at hald device */
			idpow[j] = icx_powlike_needed(hdv, thdv); 
			
		}
	}

	if (verb > 1) {
		printf("Abs DE values:\n");
		for (i = 0; i < PRES; i++) {
			co tp;	/* Test point */
			tp.p[0]= i/(double)(PRES-1);

			printf("  dev %f, aDE",tp.p[0]);
			for (j = 0; j < 6 && j < devchan; j++) {
				ade[j]->interp(ade[j], &tp);
				printf(" %f",tp.v[0]);
			}
			printf("\n");
		}
		printf("Rel DE values:\n");
		for (i = 0; i < PRES; i++) {
			co tp;	/* Test point */
			tp.p[0]= i/(double)(PRES-1);

			printf("  dev %f, rdev",tp.p[0]);
			for (j = 0; j < 6 && j < devchan; j++) {
				rde[j]->interp(rde[j], &tp);
				printf(" %f",tp.v[0]);
			}
			printf("\n");
		}
	}

	if (initial || recal) {
		if (verb && pct->is_set(pct))  {
			for (j = 0; j < devchan; j++) {
				printf("Chan %d Dev max %f, aDE Max %f, aDE Min %f\n",j,pct->devmax[j],pct->ademax[j],pct->ademin[j]);
			}
		}

		if (verb)  {
			double avgpow = 0.0;
			for (j = 0; j < devchan; j++) {
				printf("Chan %d ideal targen power = %f\n",j,idpow[j]);
				avgpow += idpow[j];
			}
			avgpow /= (double)devchan;
			printf("Average ideal targen power = %f\n",avgpow);
		}
	}

	/* Plot both the delta E curves, and markers */
	if (doplot) {
		co tp;	/* Test point */
		double xx[PRES];
		double yy[10][PRES];
		double cx[10], cy[10];
		int nmark;

		printf("Absolute DE plot:\n");

		for (i = 0; i < PRES; i++) {
			xx[i] = i/(double)(PRES-1);

			for (j = 0; j < 10 && j < devchan; j++) {
				tp.p[0] = xx[i];
				ade[j]->interp(ade[j], &tp);
				yy[j][i] = tp.v[0];
			}
		}
		nmark = 0;
		if (pct->is_set(pct)) {
			/* Add markers for deMax */
			for (j = 0; j < 10 && j < devchan; j++) {
				cx[j] = pct->devmax[j];
				cy[j] = pct->ademax[j];
				nmark++;
			}
		}
		do_plot10p(xx, devchan > 3 ? yy[3] : NULL,
		               devchan > 1 ? yy[1] : NULL,
		               devchan > 4 ? yy[4] : NULL,
		               devchan > 0 ? yy[0] : NULL,
		               devchan > 2 ? yy[2] : NULL,
		               devchan > 5 ? yy[5] : NULL,
		               devchan > 6 ? yy[6] : NULL,
		               devchan > 7 ? yy[7] : NULL,
		               devchan > 8 ? yy[8] : NULL,
		               devchan > 9 ? yy[9] : NULL,
		               PRES,
					   cx, cy, verify ? 0 : nmark);

		printf("Relative DE plot:\n");

		for (i = 0; i < PRES; i++) {
			xx[i] = i/(double)(PRES-1.0);

			for (j = 0; j < 10 && j < devchan; j++) {
				tp.p[0] = xx[i];
				rde[j]->interp(rde[j], &tp);
				yy[j][i] = tp.v[0];
			}
		}
		nmark = 0;
		if (pct->is_set(pct)) {
			/* Add markers for deMax */
			for (j = 0; j < 10 && j < devchan; j++) {
				cx[j] = pct->devmax[j];
				tp.p[0] = cx[j];
				rde[j]->interp(rde[j], &tp);
				cy[j] = tp.v[0];
				nmark++;
			}
		}
		do_plot10p(xx, devchan > 3 ? yy[3] : NULL,
		             devchan > 1 ? yy[1] : NULL,
		             devchan > 4 ? yy[4] : NULL,
		             devchan > 0 ? yy[0] : NULL,
		             devchan > 2 ? yy[2] : NULL,
		             devchan > 5 ? yy[5] : NULL,
		             devchan > 6 ? yy[6] : NULL,
		             devchan > 7 ? yy[7] : NULL,
		             devchan > 8 ? yy[8] : NULL,
		             devchan > 9 ? yy[9] : NULL,
		             PRES,
					 cx, cy, verify ? 0 : nmark);

		if (idpow[0] > 0.0) {
			printf("Relative DE plot with ideal targen power applied:\n");

			for (i = 0; i < PRES; i++) {
				xx[i] = i/(double)(PRES-1.0);
	
				for (j = 0; j < 10 && j < devchan; j++) {
					tp.p[0] = icx_powlike(xx[i],idpow[j]);
					rde[j]->interp(rde[j], &tp);
					yy[j][i] = tp.v[0];
				}
			}
			nmark = 0;
			if (pct->is_set(pct)) {
				/* Add markers for deMax */
				for (j = 0; j < 10 && j < devchan; j++) {
					cx[j] = pct->devmax[j];
					tp.p[0] = icx_powlike(cx[j],idpow[j]);
					rde[j]->interp(rde[j], &tp);
					cy[j] = tp.v[0];
					nmark++;
				}
			}
			do_plot10p(xx, devchan > 3 ? yy[3] : NULL,
			             devchan > 1 ? yy[1] : NULL,
			             devchan > 4 ? yy[4] : NULL,
			             devchan > 0 ? yy[0] : NULL,
			             devchan > 2 ? yy[2] : NULL,
			             devchan > 5 ? yy[5] : NULL,
			             devchan > 6 ? yy[6] : NULL,
			             devchan > 7 ? yy[7] : NULL,
			             devchan > 8 ? yy[8] : NULL,
			             devchan > 9 ? yy[9] : NULL,
			             PRES,
						 cx, cy, verify ? 0 : nmark);
		}
	}

	/* Compare the previous expected aDE against the current one */
	if (verify) {
		co tp;	/* Test point */
		double avg[MAX_CHAN];
		double max[MAX_CHAN];
		double rms[MAX_CHAN];
		int verified = 1;

		/* Verify each channel */
		for (j = 0; j < devchan; j++) {
			co tp;

			avg[j] = 0.0;
			max[j] = -1.0;
			rms[j] = 0.0;

			/* Sample it at GRES */
			for (i = 0; i < GRES; i++) {
				double iv, targ, val, tt;

				iv = i/(GRES-1.0);

				/* Lookup the ade that we expect */ 
				tp.p[0] = iv;
				pcade[j]->interp(pcade[j], &tp);
				targ = tp.v[0];

				/* Lookup the ade that we have */ 
				tp.p[0] = iv;
				ade[j]->interp(ade[j], &tp);
				val = tp.v[0];

				/* Compute the stats */
				tt = fabs(targ - val);
				avg[j] += tt;
				rms[j] += tt * tt;
				if (tt > max[j])
					max[j] = tt;
//printf("~1 chan %d, ix %d, iv %f, targ %f, actual %f, err %f\n",j,i,iv,targ,val,tt);
			}
			avg[j] /= (double)GRES;
			rms[j] /= (double)GRES;
			rms[j] = sqrt(rms[j]);
			if (max[j] > ver_maxde)
				verified = 0;
		}
		if (verb) {
			for (j = 0; j < devchan; j++) {
				printf("Verify results:\n");
				printf("Channel %d has DE avg %.1f, rms %.1f, max %.1f\n",j,avg[j],rms[j],max[j]);
			}
			if (verified)
				printf("Verified OK\n");
			else
				printf("Verification FAILED\n");
		}

		/* Plot the verification curves */
		if (doplot) {
			double xx[PRES];
			double yy[10][PRES];
	
			printf("Verification match plot:\n");

			for (j = 0; j < 6 && j < devchan; j++) {
				co tp;	/* Test point */
				double max;

				/* Establish the scale */
				tp.p[0] = 1.0;
				pcade[j]->interp(pcade[j], &tp);
				max = tp.v[0];

				for (i = 0; i < PRES; i++) {
					xx[i] = i/(double)(PRES-1);

					/* Convert ade target to device */
					tp.v[0] = max * xx[i];
					if ((tp.p[0] = rspl_ilookup(pcade[j], 1.0, tp.v[0])) < 0.0)
						error("Unexpected failure to invert curve %d for pcADE %f",j,tp.v[0]); 
					/* Convert device to actual ade */
					ade[j]->interp(ade[j], &tp);
					if (fabs(max) > 0.1)
						yy[j][i] = tp.v[0]/max;
					else
						yy[j][i] = 0.0;
				}
			}
			do_plot10(xx, devchan > 3 ? yy[3] : NULL,
						  devchan > 1 ? yy[1] : NULL,
						  devchan > 4 ? yy[4] : NULL,
						  devchan > 0 ? yy[0] : NULL,
						  devchan > 2 ? yy[2] : NULL,
						  devchan > 5 ? yy[5] : NULL,
		                  devchan > 6 ? yy[6] : NULL,
		                  devchan > 7 ? yy[7] : NULL,
		                  devchan > 8 ? yy[8] : NULL,
		                  devchan > 9 ? yy[9] : NULL,
			              PRES, 0);
			if (!verified)
				exit(1);
		}
	} else if (initial) {

		/* Convert any transfer curve target points into a smooth curve */ 
		if (pct->no_tpoints > 0) {
			int gres[MXDI] = { GRES };
			co *pnts;
		
			if ((pnts = (co *)calloc(pct->no_tpoints + 2, sizeof(co))) == NULL)
				error ("Malloc of rspl points failed");
	
			for (j = 0; j < devchan; j++) {
				int npts;
				int gotmin, gotmax;
	
				/* Count the number of valid points */
				for (npts = i = 0; i < pct->no_tpoints; i++) {
					if (pct->tpoints[i].val[j] >= 0.0)
						npts++;
				}
				if (npts == 0)
					continue;		/* No target curve for this channel */
	
				if ((tcurves[j] = new_rspl(RSPL_NOFLAGS, 1, 1)) == NULL)
					error("new_rspl(1,1) failed");
				
				gotmin = gotmax = 0;
				for (npts = i = 0; i < pct->no_tpoints; i++) {
					if (pct->tpoints[i].val[j] < 0.0)
						continue;
	
					pnts[npts].p[0] = pct->tpoints[i].loc;
					pnts[npts].v[0] = pct->tpoints[i].val[j];
					if (pnts[npts].p[0] < 0.0)
						pnts[npts].p[0] = 0.0;
					else if (pnts[npts].p[0] > 1.0)
						pnts[npts].p[0] = 1.0;
					if (pnts[npts].v[0] < 0.0)
						pnts[npts].v[0] = 0.0;
					else if (pnts[npts].v[0] > 1.0)
						pnts[npts].v[0] = 1.0;
	
					if (pnts[npts].p[0] <= 0.05)
						gotmin = 1;
					if (pnts[npts].p[0] >= 0.95)
						gotmax = 1;
					npts++;
				}
				/* Add default anchors if there are none supplied */
				if (gotmin == 0) {
					pnts[npts].p[0] = 0.0;
					pnts[npts++].v[0] = 0.0;
				}
				if (gotmax == 0) {
					pnts[npts].p[0] = 1.0;
					pnts[npts++].v[0] = 1.0;
				}
	
				/* Fit the curve to the given points */
				tcurves[j]->fit_rspl(tcurves[j], RSPLFLAGS, pnts, npts,
				                NULL, NULL, gres, NULL, NULL, TCURVESMOOTH, NULL, NULL); 
			}
			free(pnts);
	
			/* Plot the target curves */
			if (doplot) {
				double xx[PRES];
				double yy[10][PRES];
	
				printf("Target curves plot:\n");
	
				for (i = 0; i < (PRES-1); i++) {
					co tp;	/* Test point */
					double pp = i/(PRES-1.0);
	
					xx[i] = pp;
					for (j = 0; j < 10 && j < devchan; j++) {
						if (tcurves[j] != NULL) {
							tp.p[0] = pp;
							tcurves[j]->interp(tcurves[j], &tp);
							yy[j][i] = tp.v[0];
						} else
							yy[j][i] = pp;
					}
				}
				do_plot10(xx, devchan > 3 ? yy[3] : NULL,
							  devchan > 1 ? yy[1] : NULL,
							  devchan > 4 ? yy[4] : NULL,
							  devchan > 0 ? yy[0] : NULL,
							  devchan > 2 ? yy[2] : NULL,
							  devchan > 5 ? yy[5] : NULL,
		                      devchan > 6 ? yy[6] : NULL,
		                      devchan > 7 ? yy[7] : NULL,
		                      devchan > 8 ? yy[8] : NULL,
		                      devchan > 9 ? yy[9] : NULL,
				              PRES, 0);
			}
		}

		/* Do inverse lookup to create relative linearization curves */
		n_cvals = CAL_RES;
		for (j = 0; j < devchan; j++) {
			co tp;
			double rdemin, rdemax;	/* Relative DE min and max targets */

			/* Convert absolute de aims to relative */
			if ((rdemax = rspl_ilookup(ade[j], 0.0, pct->ademax[j])) < 0.0)
				error("Unexpected failure to invert curve %d for DE %f",j,pct->ademax[j]); 

			tp.p[0] = rdemax;
			rde[j]->interp(rde[j], &tp);
			rdemax = tp.v[0];

			if ((rdemin = rspl_ilookup(ade[j], 1.0, pct->ademin[j])) < 0.0)
				error("Unexpected failure to invert curve %d for DE %f",j,pct->ademax[j]); 

			tp.p[0] = rdemin;
			rde[j]->interp(rde[j], &tp);
			rdemin = tp.v[0];

			if (verb > 0)
				printf("Chan %d: rDE Max = %f, rDE Min = %f\n",j,rdemax,rdemin);

			if ((cvals[j] = (wval *)malloc(sizeof(wval) * n_cvals)) == NULL)
				error("Malloc of %d cvals failed",n_cvals);

			/* Convert relative delta E aim to device value */
			for (i = 0; i < n_cvals; i++) {
				double x = i/(n_cvals-1.0);
				double inv;

				cvals[j][i].inv = x;

				/* Apply any aim tweak curve */
				if (tcurves[j] != NULL) {
					tp.p[0] = x;
					tcurves[j]->interp(tcurves[j], &tp);
					x = tp.v[0];
				}

				inv = x * (rdemax - rdemin) + rdemin;

				if ((cvals[j][i].dev = rspl_ilookup(rde[j], 0.5, inv)) < 0.0)
					error("Unexpected failure to invert curve %d for DE %f",j,inv); 
//printf("~1 chan %d, step %d, inv %f, detarg %f, got dev %f\n",j,i,x,pp[0].v[0],pp[k].p[0]);
			}
		}

	} else if (recal || imitate) {

		n_cvals = CAL_RES;
		for (j = 0; j < devchan; j++) {
			co tp;

			if ((cvals[j] = (wval *)malloc(sizeof(wval) * n_cvals)) == NULL)
				error("Malloc of %d cvals failed",n_cvals);

			/* Lookup the expected ade for each input device value, and */
			/* then translate it into the required output device value */
			for (i = 0; i < n_cvals; i++) {
				double x = i/(n_cvals-1.0);

				cvals[j][i].inv = tp.p[0] = x;
				pcade[j]->interp(pcade[j], &tp);

				if ((cvals[j][i].dev = rspl_ilookup(ade[j], 0.5, tp.v[0])) < 0.0)
					error("Unexpected failure to invert curve %d for DE %f",j,tp.v[0]); 
//printf("~1 chan %d, ix %d, inv %f, pcade %f, iade %f\n",j,i,x,tp.v[0],cvals[j][i].dev);
			}
		}
	}

	if (initial || recal || imitate) {

		if (verb > 1) {
			printf("Calibration curve values:\n");
			for (i = 0; i < n_cvals; i++) {
				printf("  inv %f, dev",cvals[0][i].inv);
				for (j = 0; j < devchan; j++) {
					printf(" %f",cvals[j][i].dev);
				}
				printf("\n");
			}
		}

		/* Plot the calibration curves */
		if (doplot) {
			double xx[PRES];
			double yy[10][PRES];

			printf("Calibration curve plot:\n");

			for (i = 0; i < n_cvals; i++) {
				xx[i] = cvals[0][i].inv;
				for (j = 0; j < 10 && j < devchan; j++) {
					yy[j][i] = cvals[j][i].dev;
				}
			}
			do_plot10(xx, devchan > 3 ? yy[3] : NULL,	/* Black */
			              devchan > 1 ? yy[1] : NULL,	/* Red */
			              devchan > 4 ? yy[4] : NULL,	/* Green */
			              devchan > 0 ? yy[0] : NULL,	/* Blue */
			              devchan > 2 ? yy[2] : NULL,	/* Yellow */
			              devchan > 5 ? yy[5] : NULL,	/* Purple */
		                  devchan > 6 ? yy[6] : NULL,	/* Brown */
		                  devchan > 7 ? yy[7] : NULL,	/* Orange */
		                  devchan > 8 ? yy[8] : NULL,	/* Grey */
		                  devchan > 9 ? yy[9] : NULL,	/* White */
			              PRES, 0);
		}

		/* Write out an Argyll .CAL file */
		if (dowrite) {
			cgats *ocg;						/* output cgats structure */
			time_t clk = time(0);
			struct tm *tsp = localtime(&clk);
			char *atm = asctime(tsp);		/* Ascii time */
			char *ident = icx_inkmask2char(devmask, 1); 
			char *bident = icx_inkmask2char(devmask, 0); 
			cgats_set_elem *setel;			/* Array of set value elements */
			int nsetel = 0;
			int ncps;						/* Number of curve parameters */
			double *cps[3];					/* Arrays of curve parameters */
			char *bp = NULL, buf[100];		/* Buffer to sprintf into */
			co tp;

			ocg = new_cgats();				/* Create a CGATS structure */
			ocg->add_other(ocg, "CAL"); 	/* our special type is Calibration file */

			ocg->add_table(ocg, tt_other, 0);	/* Add a table for RAMDAC values */
			ocg->add_kword(ocg, 0, "DESCRIPTOR", "Argyll Device Calibration Curves",NULL);
			ocg->add_kword(ocg, 0, "ORIGINATOR", "Argyll printcal", NULL);
			atm[strlen(atm)-1] = '\000';	/* Remove \n from end */
			ocg->add_kword(ocg, 0, "CREATED",atm, NULL);

			ocg->add_kword(ocg, 0, "DEVICE_CLASS","OUTPUT", NULL);
			ocg->add_kword(ocg, 0, "COLOR_REP", ident, NULL);

			if (xpi.deviceMfgDesc != NULL)
				ocg->add_kword(ocg, 0, "MANUFACTURER", xpi.deviceMfgDesc, NULL);
			if (xpi.modelDesc != NULL)
				ocg->add_kword(ocg, 0, "MODEL", xpi.modelDesc, NULL);
			if (xpi.profDesc != NULL)
				ocg->add_kword(ocg, 0, "DESCRIPTION", xpi.profDesc, NULL);
			if (xpi.copyright != NULL)
				ocg->add_kword(ocg, 0, "COPYRIGHT", xpi.copyright, NULL);

			/* Setup the table which holds the translation from calibrated */
			/* device value "I" to the raw device channel value */ 
			sprintf(buf, "%s_I",bident);
			ocg->add_field(ocg, 0, buf, r_t);
			nsetel++;
			for (j = 0; j < devchan; j++) {
				inkmask imask = icx_index2ink(devmask, j);
				sprintf(buf, "%s_%s",bident,icx_ink2char(imask));
				ocg->add_field(ocg, 0, buf, r_t);
				nsetel++;
			}
			if ((setel = (cgats_set_elem *)malloc(sizeof(cgats_set_elem) * nsetel)) == NULL)
				error("Malloc failed!");

			/* Write the per channel device to device loolup curve values */
			if (devmask & ICX_ADDITIVE) {
				for (i = n_cvals-1; i >= 0; i--) {
		
					setel[0].d = 1.0 - cvals[0][i].inv;
					for (j = 0; j < devchan; j++)
						setel[1+j].d = 1.0 - cvals[j][i].dev;
					ocg->add_setarr(ocg, 0, setel);
				}
			} else {
				for (i = 0; i < n_cvals; i++) {
		
					setel[0].d = cvals[0][i].inv;
					for (j = 0; j < devchan; j++)
						setel[1+j].d = cvals[j][i].dev;
					ocg->add_setarr(ocg, 0, setel);
				}
			}

			free(setel);

			/* Write the calibration target information to a second table */
			if (pct->write(pct, ocg, 1) != 0)
				error("Writing cal target info to cal file '%s'",outname);

			/* Add a third table which is the expected absolute DE response */
			/* of the calibrated device. */
			ocg->add_table(ocg, tt_other, 0);	/* Add a table for RAMDAC values */
			ocg->add_kword(ocg, 2, "DESCRIPTOR", "Argyll Output Calibration Expected DE Response",NULL);
			ocg->add_kword(ocg, 2, "ORIGINATOR", "Argyll printcal", NULL);
			atm[strlen(atm)-1] = '\000';	/* Remove \n from end */
			ocg->add_kword(ocg, 2, "CREATED",atm, NULL);

			ocg->add_kword(ocg, 2, "DEVICE_CLASS","OUTPUT", NULL);
			ocg->add_kword(ocg, 2, "COLOR_REP", ident, NULL);

			/* Setup the table which holds the translation from calibrated */
			/* device value "I" to the expected absolute deltaE value for */
			/* each colorant. */
			sprintf(buf, "%s_I_DE",bident);
			ocg->add_field(ocg, 2, buf, r_t);
			nsetel++;
			for (j = 0; j < devchan; j++) {
				inkmask imask = icx_index2ink(devmask, j);
				sprintf(buf, "%s_%s_DE",bident,icx_ink2char(imask));
				ocg->add_field(ocg, 2, buf, r_t);
				nsetel++;
			}
			if ((setel = (cgats_set_elem *)malloc(sizeof(cgats_set_elem) * nsetel)) == NULL)
				error("Malloc failed!");

			for (i = 0; i < n_cvals; i++) {
				int ix = i;

				/* Calibrated device value */
				if (devmask & ICX_ADDITIVE) {
					ix = n_cvals -1 - i;
					setel[0].d = 1.0 - cvals[0][ix].inv;
				} else
					setel[0].d = cvals[0][ix].inv;

				for (j = 0; j < devchan; j++) {
					tp.p[0] = cvals[j][ix].dev;		/* Raw device value */
					ade[j]->interp(ade[j], &tp);	/* Corresponding ade value */
					setel[1+j].d = tp.v[0];
				}
				ocg->add_setarr(ocg, 2, setel);
			}

			free(setel);

			if (ocg->write_name(ocg, outname))
				error("Write error to file '%s': %s",outname,ocg->err);

			if (verb)
				printf("Written calibration file '%s'\n",outname);

			ocg->del(ocg);		/* Clean up */
			free(ident);
			free(bident);
		}

		/* 
			The structure of *.AMP is very simple.
	
				It has 5 tables that have
					256 entries that are 8-bit (byte), even for 16 bit mode.
			
						The first table 0000..00FFh is the CMYK channel.
						The second table 0100..01FFh is the C channel.
						The third table 0200..02FFh is the M channel.
						The fourth table 0300..03FFh is the Y channel.
						The fifth table 0300..03FFh is the K channel.
			
						Table position nn00h is the black end and table position nnFFh
						is the white end.
			
		*/

		/* Write an Adobe map format (.AMP) file */
		/* (It's not clear if more than 4 channels is allowed) */
		if (dowrite && doamp) {
			FILE *fp;
			cgatsFile *p;
			char nmode[50] = { '\000' };

			strcpy(nmode, "w");
#if defined(O_BINARY) || defined(_O_BINARY)
			strcat(nmode, "b");
#endif
			if ((fp = fopen(ampname, nmode)) == NULL)
				error("Couldn't open '%s' for writing",ampname);
			
			/* CMYK table is unity */
			for (i = 0; i < 256; i++) {
				if (putc(i,fp) == EOF)
					error("Error writing to fle '%s'",ampname);
			}
			for (j = 0; j < devchan; j++) {
				for (i = 0; i < 256; i++) {
					int x;
					if (devmask & ICX_ADDITIVE)
						x = (int)(cvals[j][i].dev * 255.0 + 0.5);		/* ??? */
					else
						x = 255 - (int)(cvals[j][255 - i].dev * 255.0 + 0.5);
					if (putc(x,fp) == EOF)
						error("Error writing to fle '%s'",ampname);
//printf("~1 chan %d, inv %d, dev %d\n",j,i,x);
				}
			}
			/* Extra 1:1 table */
			for (i = 0; i < 256; i++) {
				if (putc(i,fp) == EOF)
					error("Error writing to fle '%s'",ampname);
			}

			if (fclose(fp) != 0)
				error("Closing '%s' failed",ampname);

			if (verb)
				printf("Written calibration curves to '%s'\n",ampname);
		}
	}

	/* Free up various possible allocations */
	for (j = 0; j < devchan; j++) {
		if (pvals[j] != NULL)
			free(pvals[j]);
		if (raw[j] != NULL)
			raw[j]->del(raw[j]);
		if (ade[j] != NULL)
			ade[j]->del(ade[j]);
		if (rde[j] != NULL)
			rde[j]->del(rde[j]);
		if (pcade[j] != NULL)
			pcade[j]->del(pcade[j]);
		if (cvals[j] != NULL)
			free(cvals[j]);
		if (tcurves[j] != NULL)
			tcurves[j]->del(tcurves[j]);
	}

	return 0;
}