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


/* 
 * Argyll Color Correction System
 * Common display patch reading support.
 *
 * Author: Graeme W. Gill
 * Date:   2/11/2005
 *
 * Copyright 1998 - 2013 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.
 */

/* 
	TTBD:

		If verb, report white/black drift

		Should add option to ask for a black cal every N readings, for spectro's
 */

#ifdef __MINGW32__
# define WINVER 0x0500
#endif

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <sys/types.h>
#include <time.h>
#include <string.h>
#include "copyright.h"
#include "aconfig.h"
#include "numlib.h"
#include "xspect.h"
#include "insttypes.h"
#include "conv.h"
#include "icoms.h"
#include "inst.h"
#include "spyd2.h"
#include "dispwin.h"
#include "dispsup.h"
#include "webwin.h"
#ifdef NT
# include "madvrwin.h"
#endif
#include "instappsup.h"

#undef SIMPLE_MODEL		/* Make fake device well behaved */
						/* else has offsets, quantization, noise etc. */

#define DRIFT_IPERIOD	40	/* Number of samples between drift interpolation measurements */
#define DRIFT_EPERIOD	20	/* Number of samples between drift extrapolation measurements */
//#define DRIFT_IPERIOD	6	/* Test values */
//#define DRIFT_EPERIOD	3

#ifdef SIMPLE_MODEL
# undef FAKE_NOISE			/* Add noise to _fake_ devices XYZ */
# undef FAKE_UNPREDIC		/* Initialise random unpredictably */
# undef FAKE_BITS 			/* Number of bits of significance of fake device */
#else
# define FAKE_NOISE 0.01		/* Add noise to _fake_ devices XYZ */
# define FAKE_UNPREDIC			/* Initialise random unpredictably */
# define FAKE_BITS 9			/* Number of bits of significance of fake device */
#endif


/* -------------------------------------------------------- */
/* A default callback that can be provided as an argument to */
/* inst_handle_calibrate() to handle the display part of a */
/* calibration callback. */
/* Call this again with calc = inst_calc_none to cleanup afterwards. */
inst_code setup_display_calibrate(
	inst *p,
	inst_cal_cond calc,		/* Current condition. inst_calc_none for not setup */
	disp_win_info *dwi		/* Information to be able to open a display test patch */
) {
	inst_code rv = inst_ok, ev;
	dispwin *dw;	/* Display window to display test patches on, NULL if none. */
	a1logd(p->log,1,"setup_display_calibrate called with calc = 0x%x\n",calc);

	switch (calc) {
		case inst_calc_none:		/* Use this as a cleanup flag */
			if (dwi->dw == NULL && dwi->_dw != NULL) {
				dwi->_dw->del(dwi->_dw);
				dwi->_dw = NULL;
			}
			break;

		case inst_calc_emis_white:
		case inst_calc_emis_80pc:
		case inst_calc_emis_grey:
		case inst_calc_emis_grey_darker: 
		case inst_calc_emis_grey_ligher:
			if (dwi->dw == NULL) {
				if (dwi->webdisp != 0) {
					if ((dwi->_dw = new_webwin(dwi->webdisp, dwi->hpatsize, dwi->vpatsize,
						         dwi->ho, dwi->vo, 0, 0, NULL, NULL, dwi->out_tvenc, dwi->blackbg,
					             p->log->verb, p->log->debug)) == NULL) {
						a1logd(p->log,1,"inst_handle_calibrate failed to create test window 0x%x\n",inst_other_error);
						return inst_other_error; 
					}
#ifdef NT
				} else if (dwi->madvrdisp != 0) {
					if ((dwi->_dw = new_madvrwin(dwi->hpatsize, dwi->vpatsize,
					             dwi->ho, dwi->vo, 0, 0, NULL, NULL, dwi->out_tvenc, dwi->blackbg,
					             p->log->verb, p->log->debug)) == NULL) {
						a1logd(p->log,1,"inst_handle_calibrate failed to create test window 0x%x\n",inst_other_error);
						return inst_other_error; 
					}
#endif /* NT */
				} else {
					if ((dwi->_dw = new_dispwin(dwi->disp, dwi->hpatsize, dwi->vpatsize,
					             dwi->ho, dwi->vo, 0, 0, NULL, NULL, dwi->out_tvenc, dwi->blackbg,
					             dwi->override, p->log->debug)) == NULL) {
						a1logd(p->log,1,"inst_handle_calibrate failed to create test window 0x%x\n",inst_other_error);
						return inst_other_error; 
					}
				}
				printf("Calibration: Place instrument on test window.\n");
				printf(" Hit any key to continue,\n"); 
				printf(" or hit Esc or Q to abort:"); 
			} else {
				dwi->_dw = dwi->dw;
			}

			if (calc == inst_calc_emis_white) {
				p->cal_gy_level = 1.0;
				dwi->_dw->set_color(dwi->_dw, 1.0, 1.0, 1.0);

			} else if (calc == inst_calc_emis_80pc) {
				p->cal_gy_level = 0.8;
				dwi->_dw->set_color(dwi->_dw, 0.8, 0.8, 0.8);

			} else  {
				if (calc == inst_calc_emis_grey) {
					p->cal_gy_level = 0.6;
					p->cal_gy_count = 0;
				} else if (calc == inst_calc_emis_grey_darker) {
					p->cal_gy_level *= 0.7;
					p->cal_gy_count++;
				} else if (calc == inst_calc_emis_grey_ligher) {
					p->cal_gy_level *= 1.4;
					if (p->cal_gy_level > 1.0)
						p->cal_gy_level = 1.0;
					p->cal_gy_count++;
				}
				if (p->cal_gy_count > 4) {
					printf("Cell ratio calibration failed - too many tries at setting grey level.\n");
					a1logd(p->log,1,"inst_handle_calibrate too many tries at setting grey level 0x%x\n",inst_internal_error);
					return inst_internal_error; 
				}
				dwi->_dw->set_color(dwi->_dw, p->cal_gy_level, p->cal_gy_level, p->cal_gy_level);
			}
			break;

		default:
			/* Something isn't being handled */
			a1logd(p->log,1,"inst_handle_calibrate unhandled calc case 0x%x, err 0x%x\n",calc,inst_internal_error);
			return inst_internal_error;
	}
	return inst_ok;
}

/* -------------------------------------------------------- */
/* User requested calibration of the display instrument */
/* Do all available non-deferrable calibrations */
/* Should add an argument to be able to select type of calibration, */
/* rather than guessing what the user wants ? */
int disprd_calibration(
icompath *ipath,		/* Instrument path to open, &icomFakeDevice == fake */
flow_control fc,		/* Serial flow control */
int dtype,				/* Display type selection character */
int docbid,				/* NZ to only allow cbid dtypes */
int tele,				/* NZ for tele mode, falls back to spot mode */
int nadaptive,			/* NZ for non-adaptive mode */ 
int noinitcal,			/* NZ to disable initial instrument calibration */
disppath *disp,			/* display to calibrate. */
int webdisp,			/* If nz, port number for web display */
#ifdef NT
int madvrdisp,		/* NZ for MadVR display */
#endif
int out_tvenc,			/* 1 = use RGB Video Level encoding */
int blackbg,			/* NZ if whole screen should be filled with black */
int override,			/* Override_redirect on X11 */
double hpatsize,		/* Size of dispwin */
double vpatsize,
double ho, double vo,	/* Position of dispwin */
a1log *log				/* Verb, debug & error log */
) {
	instType itype = instUnknown;
	inst *p = NULL;
	int c;
	inst_code rv;
	baud_rate br = baud_19200;
	disp_win_info dwi;
	inst_cal_type calt = inst_calt_needed;
	inst_mode  cap;
	inst2_capability cap2;
	inst3_capability cap3;
	inst_mode mode = 0;

	memset((void *)&dwi, 0, sizeof(disp_win_info));
	dwi.webdisp = webdisp; 
#ifdef NT
	dwi.madvrdisp = madvrdisp; 
#endif
	dwi.disp = disp; 
	dwi.out_tvenc = out_tvenc;
	dwi.blackbg = blackbg;
	dwi.override = override;
	dwi.hpatsize = hpatsize;
	dwi.vpatsize = vpatsize;
	dwi.ho = ho;
	dwi.vo = vo;

	a1logv(log, 1, "Setting up the instrument\n");

	if ((p = new_inst(ipath, 0, log, DUIH_FUNC_AND_CONTEXT)) == NULL) {
		a1logd(log, 1, "new_inst failed\n");
		return -1;
	}

	p->log = new_a1log_d(log);

	/* Establish communications */
	if ((rv = p->init_coms(p, br, fc, 15.0)) != inst_ok) {
		a1logd(p->log, 1, "init_coms returned '%s' (%s)\n",
		       p->inst_interp_error(p, rv), p->interp_error(p, rv));
		p->del(p);
		return -1;
	}

	/* Initialise the instrument */
	if ((rv = p->init_inst(p)) != inst_ok) {
		a1logd(log,1,"init_inst returned '%s' (%s)\n",
		       p->inst_interp_error(p, rv), p->interp_error(p, rv));
		p->del(p);
		return -1;
	}

// ~~~~9999 should we call config_inst_displ(p) instead of badly duplicating
//  the instrument setup here ???

	itype = p->get_itype(p);			/* Actual type */
	p->capabilities(p, &cap, &cap2, &cap3);

	if (tele && !IMODETST(cap, inst_mode_emis_tele)) {
		printf("Want telephoto measurement capability but instrument doesn't support it\n");
		printf("so falling back to emissive spot mode.\n");
		tele = 0;
	}
	
	if (!tele && !IMODETST(cap, inst_mode_emis_spot)) {
		printf("Want emissive spot measurement capability but instrument doesn't support it\n");
		printf("so switching to telephoto spot mode.\n");
		tele = 1;
	}
	
	/* Set to emission mode to read a display */
	if (tele)
		mode = inst_mode_emis_tele;
	else
		mode = inst_mode_emis_spot;
	if (nadaptive)
		mode |= inst_mode_emis_nonadaptive;
	
//	if (p->highres)
//		mode |= inst_mode_highres;

	/* (We're assuming spectral doesn't affect calibration ?) */

	if ((rv = p->set_mode(p, mode)) != inst_ok) {
		a1logd(log,1,"Set_mode failed with '%s' (%s)\n",
		       p->inst_interp_error(p, rv), p->interp_error(p, rv));
		return -1;
	}
	p->capabilities(p, &cap, &cap2, &cap3);

	/* Set the display type */
	if (dtype != 0) {		/* Given selection character */
		if (cap2 & inst2_disptype) {
			int ix;
			if ((ix = inst_get_disptype_index(p, dtype, docbid)) < 0) {
				a1logd(log,1,"Display type selection '%c' is not valid for instrument\n",dtype);
				p->del(p);
				return -1;
			}
		
			if ((rv = p->set_disptype(p, ix)) != inst_ok) {
				a1logd(log,1,"Setting display type failed failed with '%s' (%s)\n",
				       p->inst_interp_error(p, rv), p->interp_error(p, rv));
				p->del(p);
				return -1;
			}
		} else
			printf("Display type ignored - instrument doesn't support display type\n");
	}

	/* Disable initial calibration of machine if selected */
	if (noinitcal != 0) {
		if ((rv = p->get_set_opt(p,inst_opt_noinitcalib, 0)) != inst_ok) {
			a1logd(log,1,"Setting no-initail calibrate failed with '%s' (%s)\n",
			       p->inst_interp_error(p, rv), p->interp_error(p, rv));
			printf("Disable initial-calibrate not supported\n");
		}
	}

	/* Do the calibration */
	rv = inst_handle_calibrate(p, inst_calt_available, inst_calc_none, setup_display_calibrate, &dwi);
	setup_display_calibrate(p,inst_calc_none, &dwi); 
	if (rv == inst_unsupported) {
		printf("No calibration available for instrument in this mode\n");
	} else if (rv != inst_ok) {	/* Abort or fatal error */
		printf("Calibrate failed with '%s' (%s)\n",
	       p->inst_interp_error(p, rv), p->interp_error(p, rv));
		p->del(p);
		return -1;
	}

	/* clean up */
	p->del(p);
	a1logv(log, 1, "Finished setting up the instrument\n");

	return 0;
}

/* Set color to black after 50msec delay */
int del_set_black(void *cx) {
	disprd *p = (disprd *)cx;
	int rv;

	msec_sleep(100);
	if ((rv = p->dw->set_color(p->dw, 0.0, 0.0, 0.0)) != 0) {
		a1logd(p->log,1,"set_color() returned %d\n",rv);
		return 3;
	}
	return 0;
}

/* Take a series of readings from the display - implementation */
/* Return nz on fail/abort - see dispsup.h */
/* Use disprd_err() to interpret it */
static int disprd_read_imp(
	disprd *p,
	col *cols,		/* Array of patch colors to be tested */
	int npat, 		/* Number of patches to be tested */
	int spat,		/* Start patch index for "verb", 0 if not used */
	int tpat,		/* Total patch index for "verb", 0 if not used */
	int acr,		/* If nz, do automatic final carriage return */
	int noinc,		/* If nz, don't increment the count */
	int tc,			/* If nz, termination key */
	instClamping clamp	/* NZ if clamp XYZ/Lab to be +ve */
) {
	int j, rv;
	int patch;
	ipatch val;		/* Return value */
	int ch;			/* Character */
	int cal_type;
	char id[CALIDLEN];
	inst2_capability cap2;

	/* Setup the keyboard trigger to return our commands */
	inst_set_uih(0x0, 0xff,  DUIH_TRIG);
	inst_set_uih('q', 'q',   DUIH_ABORT);
	inst_set_uih('Q', 'Q',   DUIH_ABORT);
	inst_set_uih(0x03, 0x03, DUIH_ABORT);		/* ^c */
	inst_set_uih(0x1b, 0x1b, DUIH_ABORT);		/* Esc */

	/* Setup user termination character */
	inst_set_uih(tc, tc, DUIH_TERM);

	p->it->capabilities(p->it, NULL, &cap2, NULL);

	/* See if we should calibrate the display update */
	if (!p->update_delay_set && (cap2 & inst2_meas_disp_update) != 0) {
		int cdelay, mdelay;
		athread *th;

		/* Set white with a normal delay */
		if ((rv = p->dw->set_color(p->dw, 1.0, 1.0, 1.0)) != 0) {
			a1logd(p->log,1,"set_color() returned %d\n",rv);
			return 3;
		}
		
		/* Set a zero return delay */
		cdelay = p->dw->set_update_delay(p->dw, 0);

		/* Set black 50msec after this call */
		if ((th = new_athread(del_set_black, (void *)p)) == NULL) {
			a1logd(p->log,1,"failed to create thread to set_color()\n");
			return 3;
		}
		
		/* Measure the delay */
		if ((rv = p->it->meas_delay(p->it, &mdelay)) != inst_ok) {
			a1logd(p->log,1,"warning, measure display update delay failed with '%s' (%s)\n",
				      p->it->inst_interp_error(p->it, rv), p->it->interp_error(p->it, rv));
			p->dw->set_update_delay(p->dw, cdelay);		/* Restore the default */
		} else {
			mdelay -= 100;		/* Correct for delay on set black */
			if (mdelay < 0)
				mdelay = 0;
			a1logv(p->log, 1, "Measured display update delay of %d msec",mdelay);
			mdelay += mdelay/2 + 100;
			p->dw->set_update_delay(p->dw, mdelay);
			a1logv(p->log, 1, ", using delay of %d msec\n",mdelay);
		}
		p->update_delay_set = 1;
		th->del(th);
	}

	/* See if we should do a frequency calibration or display integration time cal. first */
	if (p->it->needs_calibration(p->it) & inst_calt_ref_freq
	 && npat > 0
	 && (cols[0].r != 0.8 || cols[0].g != 0.8 || cols[0].b != 0.8)) {
		col tc;
		inst_cal_type calt = inst_calt_ref_freq;
		inst_cal_cond calc = inst_calc_emis_80pc;

		/* Hmm. Should really ask the instrument what sort of calc it needs !!! */
		if ((rv = p->dw->set_color(p->dw, 0.8, 0.8, 0.8)) != 0) {
			a1logd(p->log,1,"set_color() returned %d\n",rv);
			return 3;
		}
		/* Do calibrate, but ignore return code. Press on regardless. */
		if ((rv = p->it->calibrate(p->it, &calt, &calc, id)) != inst_ok) {
			a1logd(p->log,1,"warning, frequency calibrate failed with '%s' (%s)\n",
				      p->it->inst_interp_error(p->it, rv), p->it->interp_error(p->it, rv));
		}
	}

	/* See if we should do a display integration calibration first */
	if (p->it->needs_calibration(p->it) & inst_calt_emis_int_time) {
		col tc;
		inst_cal_type calt = inst_calt_emis_int_time;
		inst_cal_cond calc = inst_calc_emis_white;

		if ((rv = p->dw->set_color(p->dw, 1.0, 1.0, 1.0)) != 0) {
			a1logd(p->log,1,"set_color() returned %d\n",rv);
			return 3;
		}
		/* Do calibrate, but ignore return code. Press on regardless. */
		if ((rv = p->it->calibrate(p->it, &calt, &calc, id)) != inst_ok) {
			a1logd(p->log,1,"warning, display integration calibrate failed with '%s' (%s)\n",
				      p->it->inst_interp_error(p->it, rv), p->it->interp_error(p->it, rv));
		}
	}

	for (patch = 0; patch < npat; patch++) {
		col *scb = &cols[patch];
		double rgb[3];

		scb->mtype = inst_mrt_none;
		scb->XYZ_v = 0;		/* No readings are valid */
		scb->sp.spec_n = 0;
		scb->duration = 0.0;

		if (spat != 0 && tpat != 0) {
			a1logv(p->log, 1, "%cpatch %d of %d",cr_char,spat + (noinc != 0 ? 0 : patch),tpat);
			if (p->dw->set_pinfo != NULL)
				p->dw->set_pinfo(p->dw, spat + (noinc != 0 ? 0 : patch),tpat);
		}
		a1logd(p->log,1,"About to read patch %d\n",patch);

		rgb[0] = scb->r;
		rgb[1] = scb->g;
		rgb[2] = scb->b;

		/* If we are doing a soft cal, apply it to the test color */
		/* (dispwin will apply any tvenc needed) */
		if ((p->native & 1) && p->cal[0][0] >= 0.0) {
			int j;
			double inputEnt_1 = (double)(p->ncal-1);

			for (j = 0; j < 3; j++) {
				unsigned int ix;
				double val, w;
				val = rgb[j] * inputEnt_1;
				if (val < 0.0) {
					val = 0.0;
				} else if (val > inputEnt_1) {
					val = inputEnt_1;
				}
				ix = (unsigned int)floor(val);		/* Coordinate */
				if (ix > (p->ncal-2))
					ix = (p->ncal-2);
				w = val - (double)ix;		/* weight */
				val = p->cal[j][ix];
				rgb[j] = val + w * (p->cal[j][ix+1] - val);
			}
		}
		if ((rv = p->dw->set_color(p->dw, rgb[0], rgb[1], rgb[2])) != 0) {
			a1logd(p->log,1,"set_color() returned %d\n",rv);
			return 3;
		}

		/* Until we give up retrying */
		for (;;) {
			val.mtype = inst_mrt_none;
			val.XYZ_v = 0;		/* No readings are valid */
			val.sp.spec_n = 0;
			val.duration = 0.0;
	
			if ((rv = p->it->read_sample(p->it, scb->id, &val, 1)) != inst_ok
			     && (rv & inst_mask) != inst_user_trig) {
				a1logd(p->log,1,"read_sample returned '%s' (%s)\n",
			       p->it->inst_interp_error(p->it, rv), p->it->interp_error(p->it, rv));

				/* deal with a user terminate or abort */
				if ((rv & inst_mask) == inst_user_abort) {
					int keyc = inst_get_uih_char();

					/* Deal with a user terminate */
					if (keyc & DUIH_TERM) {
						return 4;

					/* Deal with a user abort */
					} else if (keyc & DUIH_ABORT) {
						empty_con_chars();
						printf("\nSample read stopped at user request!\n");
						printf("Hit Esc or Q to give up, any other key to retry:"); fflush(stdout);
						if ((ch = next_con_char()) == 0x1b || ch == 0x3 || ch == 'q' || ch == 'Q') {
							printf("\n");
							return 1;
						}
						printf("\n");
						continue;
					}

				/* Deal with needing calibration */
				} else if ((rv & inst_mask) == inst_needs_cal) {
					disp_win_info dwi;
					dwi.dw = p->dw;		/* Set window to use */
					printf("\nSample read failed because instruments needs calibration\n");
					rv = inst_handle_calibrate(p->it, inst_calt_needed, inst_calc_none,
					                                        setup_display_calibrate, &dwi);
					setup_display_calibrate(p->it, inst_calc_none, &dwi); 
					if (rv != inst_ok) {	/* Abort or fatal error */
						return 1;
					}
					continue;

				/* Deal with a bad sensor position */
				} else if ((rv & inst_mask) == inst_wrong_config) {
					empty_con_chars();
					printf("\n\nSpot read failed due to the sensor being in the wrong position\n");
					printf("(%s)\n",p->it->interp_error(p->it, rv));
					printf("Correct position then hit Esc or Q to give up, any other key to retry:"); fflush(stdout);
					if ((ch = next_con_char()) == 0x1b || ch == 0x3 || ch == 'q' || ch == 'Q') {
						printf("\n");
						return 1;
					}
					printf("\n");
					continue;

				/* Deal with a misread */
				} else if ((rv & inst_mask) == inst_misread) {
					empty_con_chars();
					printf("\nSample read failed due to misread\n");
					printf("Hit Esc or Q to give up, any other key to retry:"); fflush(stdout);
					if ((ch = next_con_char()) == 0x1b || ch == 0x3 || ch == 'q' || ch == 'Q') {
						printf("\n");
						return 1;
					}
					printf("\n");
					continue;

				/* Deal with a communications error */
				} else if ((rv & inst_mask) == inst_coms_fail) {
					empty_con_chars();
					printf("\nSample read failed due to communication problem.\n");
					printf("Hit Esc or Q to give up, any other key to retry:"); fflush(stdout);
					if ((ch = next_con_char()) == 0x1b || ch == 0x3 || ch == 'q' || ch == 'Q') {
						printf("\n");
						return 1;
					}
					printf("\n");
					if (p->it->icom->port_type(p->it->icom) == icomt_serial) {
						/* Allow retrying at a lower baud rate */
						int tt = p->it->last_scomerr(p->it);
						if (tt & (ICOM_BRK | ICOM_FER | ICOM_PER | ICOM_OER)) {
							if (p->br == baud_19200) p->br = baud_9600;
							else if (p->br == baud_9600) p->br = baud_4800;
							else if (p->br == baud_2400) p->br = baud_1200;
							else p->br = baud_1200;
						}
						if ((rv = p->it->init_coms(p->it, p->br, p->fc, 15.0)) != inst_ok) {
							a1logd(p->log,1,"init_coms returned '%s' (%s)\n",
						       p->it->inst_interp_error(p->it, rv), p->it->interp_error(p->it, rv));
							return 2;
						}
					}
				continue;
				}
			} else {
				break;		/* Sucesful reading */
			}
		}
		/* We only fall through with a valid reading */
		scb->serno = p->serno++;
		scb->msec = msec_time();

		a1logd(p->log,1, "got reading %f %f %f, transfering to col\n",
		                val.XYZ[0], val.XYZ[1], val.XYZ[2]);

		scb->mtype = val.mtype;

		/* Copy XYZ */
		if (val.XYZ_v != 0) {
			for (j = 0; j < 3; j++)
				scb->XYZ[j] = val.XYZ[j];
			scb->XYZ_v = 1;
		}

		/* Copy spectral */
		if (p->spectral && val.sp.spec_n > 0) {
			scb->sp = val.sp;
		}
		a1logd(p->log,1,"on to next reading\n");
	}
	/* Final return. */
	if (acr && spat != 0 && tpat != 0 && (spat+patch-1) == tpat)
		a1logv(p->log, 1, "\n");
	return 0;
}

/* A structure to hold info about drift samples */
typedef struct {
	col dcols[2];	/* Black and white readings */

	int off, count;	/* Offset and count into cols */

} dsamples;

/* Take a series of readings from the display - drift compensation */
/* Return nz on fail/abort - see dispsup.h */
/* Use disprd_err() to interpret it */
static int disprd_read_drift(
	disprd *p,
	col *cols,		/* Array of patch colors to be tested */
	int npat, 		/* Number of patches to be tested */
	int spat,		/* Start patch index for "verb", 0 if not used */
	int tpat,		/* Total patch index for "verb", 0 if not used */
	int acr,		/* If nz, do automatic final carriage return */
	int tc,			/* If nz, termination key */
	instClamping clamp	/* NZ if clamp XYZ/Lab to be +ve */
) {
	int rv, i, j, e;
	double fper, foff;
	int off, poff;
	int boff, eoff, dno;	/* b&w offsets and count */

//printf("~1 DRIFT_EPERIOD %d, DRIFT_IPERIOD %d, npat %d\n",DRIFT_EPERIOD,DRIFT_IPERIOD,npat);

	/* Figure number and offset for b&w */
	if (p->bdrift == 0) {	/* Must be just wdrift */
		boff = eoff = 1;
		dno = 1;
	} else if (p->wdrift == 0) {	/* Must be just bdrift */
		boff = eoff = 0;
		dno = 1;
	} else {				/* Must be both */
		boff = eoff = 0;
		dno = 2;
	}

	/* If the last drift readings are invalid or too old, */
	/* or if we will use interpolation, read b&w */
#ifdef NEVER
	printf("last_bw_v = %d (%d)\n",p->last_bw_v,p->last_bw_v == 0);
	printf("npat = %d > %d, serno %d, last serno %d (%d)\n",npat, DRIFT_EPERIOD, p->serno,p->last_bw[eoff].serno,(npat > DRIFT_EPERIOD && p->serno > p->last_bw[eoff].serno));
	printf("serno - lastserno %d > %d (%d)\n",p->serno - p->last_bw[eoff].serno, DRIFT_EPERIOD,(p->serno - p->last_bw[eoff].serno) > DRIFT_EPERIOD);
	printf("msec %d - last %d = %d > 10000 (%d)\n",msec_time(),p->last_bw[boff].msec,msec_time() - p->last_bw[boff].msec,(msec_time() - p->last_bw[eoff].msec) > 10000);
#endif /* NEVER */
	if (p->last_bw_v == 0											/* There are none */
	 || (npat > DRIFT_EPERIOD && p->serno > p->last_bw[eoff].serno)	/* We will interpolate */
	 || (p->serno - p->last_bw[eoff].serno - dno) > DRIFT_EPERIOD	/* extrapolate would be too far */
	 || (msec_time() - p->last_bw[eoff].msec) > 10000) {	/* The current is too long ago */

//printf("~1 refreshing last bw\n");
		/* Read the black and/or white drift patch */
		p->last_bw[0].r = 
		p->last_bw[0].g = 
		p->last_bw[0].b = 0.0; 
		p->last_bw[1].r = 
		p->last_bw[1].g = 
		p->last_bw[1].b = 1.0; 
		if ((rv = disprd_read_imp(p, &p->last_bw[boff], dno, spat, tpat, 0, 1, tc, 0)) != 0) {
			return rv;
		}
		p->last_bw_v = 1;

		/* If there is no reference b&w, set them from this first b&w */
		if (p->ref_bw_v == 0) {
			p->ref_bw[0] = p->last_bw[0];
			p->ref_bw[1] = p->last_bw[1];
			p->ref_bw_v = 1;
		}
	}

	/* If there are enough patches to bracket with drift readings */ 
	if (npat > DRIFT_EPERIOD) {
		int ndrift = 2;			/* Number of drift records */
		dsamples *dss;

		/* Figure out the number of drift samples we need */
		ndrift += (npat-1)/DRIFT_IPERIOD;
//printf("~1 spat %d, npat = %d, tpat %d, ndrift = %d\n",spat,npat,tpat,ndrift);

		if ((dss = (dsamples *)calloc(sizeof(dsamples), ndrift)) == NULL) {
			a1logd(p->log,1, "malloc of %d dsamples failed\n",ndrift);
			return 5;
		}
	
		/* Set up bookeeping */
		fper = (double)npat/(ndrift-1.0);
//printf("~1 fper = %f\n",fper);
		foff = 0.0;
		for (poff = off = i = 0; i < ndrift; i++) {
			dss[i].off = off;
			foff += fper;
			off = (int)floor(foff + 0.5);
			if (i < (ndrift-1))
				dss[i].count = off - poff;
			else
				dss[i].count = 0;
			poff = off;
//printf("~1 dss[%d] off = %d, count = %d\n",i, dss[i].off,dss[i].count);

			dss[i].dcols[0].r = 
			dss[i].dcols[0].g = 
			dss[i].dcols[0].b = 0.0; 
			dss[i].dcols[1].r = 
			dss[i].dcols[1].g = 
			dss[i].dcols[1].b = 1.0; 
		}

		/* For each batch of patches bracketed by drift patch readings */
		for (i = 0; i < (ndrift-1); i++) {

			if (i == 0) {	/* Already done very first drift patches, so use them */
				/* Use last b&w */
				dss[i].dcols[0] = p->last_bw[0];
				dss[i].dcols[1] = p->last_bw[1];
			} else {
				/* Read the black and/or white drift patchs before next batch */
				if ((rv = disprd_read_imp(p, &dss[i].dcols[boff], dno, spat+dss[i].off, tpat, 0, 1, tc, 0)) != 0) {
					free(dss);
					return rv;
				}
			}
			/* Read this batch of patches */
			if ((rv = disprd_read_imp(p, &cols[dss[i].off], dss[i].count,spat+dss[i].off,tpat,0,0,tc, 0)) != 0) {
				free(dss);
				return rv;
			}
		}
		/* Read the black and/or white drift patchs after last batch */
		if ((rv = disprd_read_imp(p, &dss[i].dcols[boff], dno, spat+dss[i].off-1, tpat, 0, 1, tc, 0)) != 0) {
			free(dss);
			return rv;
		}
		/* Remember the last for next time */
		p->last_bw[0] = dss[i].dcols[0];
		p->last_bw[1] = dss[i].dcols[1];
		p->last_bw_v = 1;

		/* Set the white drift target to be the last one for batch */
		p->targ_w = p->last_bw[1];
		p->targ_w_v = 1;

//printf("~1 ref b = %f %f %f\n", p->ref_bw[0].XYZ[0], p->ref_bw[0].XYZ[1], p->ref_bw[0].XYZ[2]);
//printf("~1 ref w = %f %f %f\n", p->ref_bw[1].XYZ[0], p->ref_bw[1].XYZ[1], p->ref_bw[1].XYZ[2]);
//printf("~1 ndrift-1 b = %f %f %f\n", dss[ndrift-1].dcols[0].XYZ[0], dss[ndrift-1].dcols[0].XYZ[1], dss[ndrift-1].dcols[0].XYZ[2]);
//printf("~1 ndrift-1 w = %f %f %f\n", dss[ndrift-1].dcols[1].XYZ[0], dss[ndrift-1].dcols[1].XYZ[1], dss[ndrift-1].dcols[1].XYZ[2]);

		/* Apply the drift compensation using interpolation */
		for (i = 0; i < (ndrift-1); i++) {

			for (j = 0; j < dss[i].count; j++) {
				int k = dss[i].off + j;
				double we;		/* Interpolation weight of eairlier value */
				col bb, ww;		/* Interpolated black and white */
//double uXYZ[3];
//icmCpy3(uXYZ, cols[k].XYZ);
//printf("~1 patch %d = %f %f %f\n", k, cols[k].XYZ[0], cols[k].XYZ[1], cols[k].XYZ[2]);
				if (p->bdrift) {
					we = (double)(dss[i+1].dcols[0].msec - cols[k].msec)/
					     (double)(dss[i+1].dcols[0].msec - dss[i].dcols[0].msec);

					if (cols[k].XYZ_v) {
						for (e = 0; e < 3; e++) {
							bb.XYZ[e] =        we  * dss[i].dcols[0].XYZ[e]
							          + (1.0 - we) * dss[i+1].dcols[0].XYZ[e];
						}
//printf("~1 bb = %f %f %f\n", bb.XYZ[0], bb.XYZ[1], bb.XYZ[2]);
					}
					if (cols[k].sp.spec_n > 0) {
						for (e = 0; e < cols[k].sp.spec_n; e++) {
							bb.sp.spec[e] =        we  * dss[i].dcols[0].sp.spec[e]
							          + (1.0 - we) * dss[i+1].dcols[0].sp.spec[e];
						}
					}
				}
				if (p->wdrift) {
					we = (double)(dss[i+1].dcols[1].msec - cols[k].msec)/
					     (double)(dss[i+1].dcols[1].msec - dss[i].dcols[1].msec);

					if (cols[k].XYZ_v) {
						for (e = 0; e < 3; e++) {
							ww.XYZ[e] =        we  * dss[i].dcols[1].XYZ[e]
							          + (1.0 - we) * dss[i+1].dcols[1].XYZ[e];
						}
//printf("~1 ww = %f %f %f\n", ww.XYZ[0], ww.XYZ[1], ww.XYZ[2]);
					}
					if (cols[k].sp.spec_n > 0) {
						for (e = 0; e < cols[k].sp.spec_n; e++) {
							ww.sp.spec[e] =        we  * dss[i].dcols[1].sp.spec[e]
							          + (1.0 - we) * dss[i+1].dcols[1].sp.spec[e];
						}
					}
				}

				if (p->bdrift) {
					/* Compensate interpolated black for any white change from ref. */
					if (p->wdrift) {
						if (cols[k].XYZ_v) {
							for (e = 0; e < 3; e++) {
								bb.XYZ[e] *= p->ref_bw[1].XYZ[e]/ww.XYZ[e];
							}
//printf("~1 wcomp bb = %f %f %f\n", bb.XYZ[0], bb.XYZ[1], bb.XYZ[2]);
						}
						if (cols[k].sp.spec_n > 0) {
							for (e = 0; e < cols[k].sp.spec_n; e++) {
								bb.sp.spec[e] *= p->ref_bw[1].sp.spec[e]/ww.sp.spec[e];
							}
						}
					}

					/* Compensate the reading for any black drift from ref. */
					if (cols[k].XYZ_v) {
						for (e = 0; e < 3; e++) {
							cols[k].XYZ[e] += p->ref_bw[0].XYZ[e] - bb.XYZ[e];
						}
//printf("~1 bcomp patch = %f %f %f\n",  cols[k].XYZ[0], cols[k].XYZ[1], cols[k].XYZ[2]);
					}
					if (cols[k].sp.spec_n > 0) {
						for (e = 0; e < cols[k].sp.spec_n; e++) {
							cols[k].sp.spec[e] += p->ref_bw[0].sp.spec[e] - bb.sp.spec[e];
						}
					}
				}
				/* Compensate the reading for any white drift to target white */
				if (p->wdrift) {
					if (cols[k].XYZ_v) {
						for (e = 0; e < 3; e++) {
							cols[k].XYZ[e] *= p->targ_w.XYZ[e]/ww.XYZ[e];
						}
//printf("~1 wcomp patch = %f %f %f\n",  cols[k].XYZ[0], cols[k].XYZ[1], cols[k].XYZ[2]);
					}
					if (cols[k].sp.spec_n > 0) {
						for (e = 0; e < cols[k].sp.spec_n; e++) {
							cols[k].sp.spec[e] *= p->targ_w.sp.spec[e]/ww.sp.spec[e];
						}
					}
				}
//printf("~1 %d: drift change %f DE\n",k,icmXYZLabDE(&icmD50, uXYZ, cols[k].XYZ));
			}
		}
		free(dss);

	/* Else too small a batch, use extrapolation from the last b&w */
	} else {

//printf("~1 doing small number of readings\n");
		/* Read the small number of patches */
		if ((rv = disprd_read_imp(p, cols,npat,spat,tpat,acr,0,tc,0)) != 0)
			return rv;

		if (p->targ_w_v == 0) {
			/* Set the white drift reference to be the last one */
			p->targ_w = p->last_bw[1];
			p->targ_w_v = 1;
//printf("~1 set white drift target\n");
		}

//printf("~1 ref b = %f %f %f\n", p->ref_bw[0].XYZ[0], p->ref_bw[0].XYZ[1], p->ref_bw[0].XYZ[2]);
//printf("~1 ref w = %f %f %f\n", p->ref_bw[1].XYZ[0], p->ref_bw[1].XYZ[1], p->ref_bw[1].XYZ[2]);
//printf("~1 last b = %f %f %f\n", p->last_bw[0].XYZ[0], p->last_bw[0].XYZ[1], p->last_bw[0].XYZ[2]);
//printf("~1 last w = %f %f %f\n", p->last_bw[1].XYZ[0], p->last_bw[1].XYZ[1], p->last_bw[1].XYZ[2]);
//printf("~1 target w = %f %f %f\n", p->targ_w.XYZ[0], p->targ_w.XYZ[1], p->targ_w.XYZ[2]);
		/* Apply the drift compensation using extrapolation */
		for (j = 0; j < npat; j++) {
			double we;		/* Interpolation weight of eairlier value */
			col bb, ww;		/* Interpolated black and white */

//printf("~1 patch %d = %f %f %f\n", j, cols[j].XYZ[0], cols[j].XYZ[1], cols[j].XYZ[2]);
//double uXYZ[3];
//icmCpy3(uXYZ, cols[j].XYZ);

			if (p->bdrift) {
				bb = p->last_bw[0];
//printf("~1 bb = %f %f %f\n", bb.XYZ[0], bb.XYZ[1], bb.XYZ[2]);
			}
			if (p->wdrift) {
				ww = p->last_bw[1];
//printf("~1 ww = %f %f %f\n", ww.XYZ[0], ww.XYZ[1], ww.XYZ[2]);
			}

			if (p->bdrift) {
				/* Compensate interpolated black for any white change from ref. */
				if (p->wdrift) {
					if (cols[j].XYZ_v) {
						for (e = 0; e < 3; e++) {
							bb.XYZ[e] *= p->ref_bw[1].XYZ[e]/ww.XYZ[e];
						}
//printf("~1 wcomp bb = %f %f %f\n", bb.XYZ[0], bb.XYZ[1], bb.XYZ[2]);
					}
					if (cols[j].sp.spec_n > 0) {
						for (e = 0; e < cols[j].sp.spec_n; e++) {
							bb.sp.spec[e] *= p->ref_bw[1].sp.spec[e]/ww.sp.spec[e];
						}
					}
				}

				/* Compensate the reading for any black drift from ref. */
				if (cols[j].XYZ_v) {
					for (e = 0; e < 3; e++) {
						cols[j].XYZ[e] += p->ref_bw[0].XYZ[e] - bb.XYZ[e];
					}
//printf("~1 bcomp patch = %f %f %f\n",  cols[j].XYZ[0], cols[j].XYZ[1], cols[j].XYZ[2]);
				}
				if (cols[j].sp.spec_n > 0) {
					for (e = 0; e < cols[j].sp.spec_n; e++) {
						cols[j].sp.spec[e] += p->ref_bw[0].sp.spec[e] - bb.sp.spec[e];
					}
				}
			}
			/* Compensate the reading for any white drift to target white */
			if (p->wdrift) {
				if (cols[j].XYZ_v) {
					for (e = 0; e < 3; e++) {
						cols[j].XYZ[e] *= p->targ_w.XYZ[e]/ww.XYZ[e];
					}
//printf("~1 wcomp patch = %f %f %f\n",  cols[j].XYZ[0], cols[j].XYZ[1], cols[j].XYZ[2]);
				}
				if (cols[j].sp.spec_n > 0) {
					for (e = 0; e < cols[j].sp.spec_n; e++) {
						cols[j].sp.spec[e] *= p->targ_w.sp.spec[e]/ww.sp.spec[e];
					}
				}
			}
//printf("~1 %d: drift change %f DE\n",j,icmXYZLabDE(&icmD50, uXYZ, cols[j].XYZ));
		}
	}

	if (acr && spat != 0 && tpat != 0 && (spat+npat-1) == tpat)
		a1logv(p->log, 1, "\n");

	if (clamp) {
		for (j = 0; j < npat; j++) {
			if (cols[j].XYZ_v)
				icmClamp3(cols[j].XYZ, cols[j].XYZ);
		}
	}
	return rv;
}

/* Reset the white drift target white value, for non-batch */
/* readings when white drift comp. is enabled */
static void disprd_reset_targ_w(disprd *p) {
	p->targ_w_v = 0;
}

/* Change the black/white drift compensation options. */
/* Note that this simply invalidates any reference readings, */
/* and therefore will not make for good black compensation */
/* if it is done a long time since the instrument calibration. */
static void disprd_change_drift_comp(disprd *p,
	int bdrift,			/* Flag, nz for black drift compensation */
	int wdrift			/* Flag, nz for white drift compensation */
) {
	if (p->bdrift && !bdrift) {		/* Turning black drift off */
		p->bdrift = 0;
		p->ref_bw_v = 0;
		p->last_bw_v = 0;
		p->targ_w_v = 0;

	} else if (!p->bdrift && bdrift) {	/* Turning black drift on */
		p->bdrift = 1;
		p->ref_bw_v = 0;
		p->last_bw_v = 0;
		p->targ_w_v = 0;
	}

	if (p->wdrift && !wdrift) {		/* Turning white drift off */
		p->wdrift = 0;
		p->ref_bw_v = 0;
		p->last_bw_v = 0;
		p->targ_w_v = 0;

	} else if (!p->wdrift && wdrift) {	/* Turning white drift on */
		p->wdrift = 1;
		p->ref_bw_v = 0;
		p->last_bw_v = 0;
		p->targ_w_v = 0;
	}
}

/* Take a series of readings from the display */
/* Return nz on fail/abort - see dispsup.h */
/* Use disprd_err() to interpret it */
static int disprd_read(
	disprd *p,
	col *cols,		/* Array of patch colors to be tested */
	int npat, 		/* Number of patches to be tested */
	int spat,		/* Start patch index for "verb", 0 if not used */
	int tpat,		/* Total patch index for "verb", 0 if not used */
	int acr,		/* If nz, do automatic final carriage return */
	int tc,			/* If nz, termination key */
	instClamping clamp	/* NZ if clamp XYZ/Lab to be +ve */
) {
	int rv, i;

	if (p->bdrift || p->wdrift) {
		if ((rv = disprd_read_drift(p, cols,npat,spat,tpat,acr,tc,clamp)) != 0)
			return rv;
	} else {
		if ((rv = disprd_read_imp(p, cols,npat,spat,tpat,acr,0,tc,clamp)) != 0)
			return rv;
	}

	/* Use spectral if available. */
	/* Since this is a display, assume that this is absolute spectral */
	if (p->sp2cie != NULL) {
		for (i = 0; i < npat; i++) {
			if (cols[i].sp.spec_n > 0) {
				p->sp2cie->convert(p->sp2cie, cols[i].XYZ, &cols[i].sp);
				if (clamp)
					icmClamp3(cols[i].XYZ, cols[i].XYZ);
				cols[i].XYZ_v = 1;
			}
		}
	}

	return rv;
}

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* Return the refresh mode and cbid */
static void disprd_get_disptype(disprd *p, int *refrmode, int *cbid) {
	if (refrmode != NULL)
		*refrmode = p->refrmode;
	if (cbid != NULL)
		*cbid = p->cbid;
}

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
static int config_inst_displ(disprd *p);

/* Take an ambient reading if the instrument has the capability. */
/* return nz on fail/abort - see dispsup.h */
/* Use disprd_err() to interpret it */
int disprd_ambient(
	struct _disprd *p,
	double *ambient,		/* return ambient in cd/m^2 */
	int tc					/* If nz, termination key */
) {
	inst_mode cap = 0;
	inst2_capability cap2 = 0;
	inst3_capability cap3 = 0;
	inst_opt_type trigmode = inst_opt_unknown;  /* Chosen trigger mode */
	int uswitch = 0;                /* Instrument switch is enabled */
	ipatch val;
	int rv;

	if (p->it != NULL) { /* Not fake */
		p->it->capabilities(p->it, &cap, &cap2, &cap3);
	}
	
	if (!IMODETST(cap, inst_mode_emis_ambient)) {
		printf("Need ambient measurement capability,\n");
		printf("but instrument doesn't support it\n");
		return 8;
	}

	printf("\nPlease make sure the instrument is fitted with\n");
	printf("the appropriate ambient light measuring head.\n");
	
	if ((rv = p->it->set_mode(p->it, inst_mode_emis_ambient)) != inst_ok) {
		a1logd(p->log,1,"set_mode returned '%s' (%s)\n",
		       p->it->inst_interp_error(p->it, rv), p->it->interp_error(p->it, rv));
		return 2;
	}
	if (p->it != NULL) { /* Not fake */
		p->it->capabilities(p->it, &cap, &cap2, &cap3);
	}
	
	/* Select a reasonable trigger mode */
	if (cap2 & inst2_user_switch_trig) {
		trigmode = inst_opt_trig_user_switch;
		uswitch = 1;

	/* Or go for user via uicallback trigger */
	} else if (cap2 & inst2_user_trig) {
		trigmode = inst_opt_trig_user;

	/* Or something is wrong with instrument capabilities */
	} else {
		printf("No reasonable trigger mode avilable for this instrument\n");
		return 2;
	}

	if ((rv = p->it->get_set_opt(p->it, trigmode)) != inst_ok) {
		printf("\nSetting trigger mode failed with error :'%s' (%s)\n",
       	       p->it->inst_interp_error(p->it, rv), p->it->interp_error(p->it, rv));
		return 2;
	}

	/* Setup the keyboard trigger to return our commands */
	inst_set_uih(0x0, 0xff,  DUIH_TRIG);
	inst_set_uih('q', 'q',   DUIH_ABORT);
	inst_set_uih('Q', 'Q',   DUIH_ABORT);
	inst_set_uih(0x03, 0x03, DUIH_ABORT);		/* ^c */
	inst_set_uih(0x1b, 0x1b, DUIH_ABORT);		/* Esc */

	/* Setup user termination character */
	inst_set_uih(tc, tc, DUIH_TERM);

	/* Until we give up retrying */
	for (;;) {
		char ch;
		val.mtype = inst_mrt_none;
		val.XYZ_v = 0;		/* No readings are valid */
		val.sp.spec_n = 0;
		val.duration = 0.0;

		printf("\nPlace the instrument so as to measure ambient upwards, beside the display,\n");
		if (uswitch)
			printf("Hit ESC or Q to exit, instrument switch or any other key to take a reading: ");
		else
			printf("Hit ESC or Q to exit, any other key to take a reading: ");
		fflush(stdout);

		if ((rv = p->it->read_sample(p->it, "AMBIENT", &val, 1)) != inst_ok
		     && (rv & inst_mask) != inst_user_trig) {
			a1logd(p->log,1,"read_sample returned '%s' (%s)\n",
		       p->it->inst_interp_error(p->it, rv), p->it->interp_error(p->it, rv));

			/* deal with a user terminate or abort */
			if ((rv & inst_mask) == inst_user_abort) {
				int keyc = inst_get_uih_char();

				/* Deal with a user terminate */
				if (keyc & DUIH_TERM) {
					return 4;

				/* Deal with a user abort */
				} else if (keyc & DUIH_ABORT) {
					empty_con_chars();
					printf("\nMeasure stopped at user request!\n");
					printf("Hit Esc or Q to give up, any other key to retry:"); fflush(stdout);
					if ((ch = next_con_char()) == 0x1b || ch == 0x3 || ch == 'q' || ch == 'Q') {
						printf("\n");
						return 1;
					}
					printf("\n");
					continue;
				}

			/* Deal with needs calibration */
			} else if ((rv & inst_mask) == inst_needs_cal) {
				disp_win_info dwi;
				dwi.dw = p->dw;		/* Set window to use */
				printf("\nSample read failed because instruments needs calibration\n");
				rv = inst_handle_calibrate(p->it, inst_calt_needed, inst_calc_none,
				                                        setup_display_calibrate, &dwi);
				setup_display_calibrate(p->it,inst_calc_none, &dwi); 
				if (rv != inst_ok) {	/* Abort or fatal error */
					return 1;
				}
				continue;

			/* Deal with a bad sensor position */
			} else if ((rv & inst_mask) == inst_wrong_config) {
				empty_con_chars();
				printf("\n\nSpot read failed due to the sensor being in the wrong position\n");
				printf("(%s)\n",p->it->interp_error(p->it, rv));
				printf("Correct position then hit Esc or Q to give up, any other key to retry:"); fflush(stdout);
				if ((ch = next_con_char()) == 0x1b || ch == 0x3 || ch == 'q' || ch == 'Q') {
					printf("\n");
					return 1;
				}
				printf("\n");
				continue;

			/* Deal with a misread */
			} else if ((rv & inst_mask) == inst_misread) {
				empty_con_chars();
				printf("\nMeasurement failed due to misread\n");
				printf("Hit Esc or Q to give up, any other key to retry:"); fflush(stdout);
				if ((ch = next_con_char()) == 0x1b || ch == 0x3 || ch == 'q' || ch == 'Q') {
					printf("\n");
					return 1;
				}
				printf("\n");
				continue;

			/* Deal with a communications error */
			} else if ((rv & inst_mask) == inst_coms_fail) {
				empty_con_chars();
				printf("\nMeasurement read failed due to communication problem.\n");
				printf("Hit Esc or Q to give up, any other key to retry:"); fflush(stdout);
				if ((ch = next_con_char()) == 0x1b || ch == 0x3 || ch == 'q' || ch == 'Q') {
					printf("\n");
					return 1;
				}
				printf("\n");
				if (p->it->icom->port_type(p->it->icom) == icomt_serial) {
					/* Allow retrying at a lower baud rate */
					int tt = p->it->last_scomerr(p->it);
					if (tt & (ICOM_BRK | ICOM_FER | ICOM_PER | ICOM_OER)) {
						if (p->br == baud_19200) p->br = baud_9600;
						else if (p->br == baud_9600) p->br = baud_4800;
						else if (p->br == baud_2400) p->br = baud_1200;
						else p->br = baud_1200;
					}
					if ((rv = p->it->init_coms(p->it, p->br, p->fc, 15.0)) != inst_ok) {
						a1logd(p->log,1,"init_coms returned '%s' (%s)\n",
					       p->it->inst_interp_error(p->it, rv), p->it->interp_error(p->it, rv));
						return 2;
					}
				}
			continue;
			}
		} else {
			break;		/* Sucesful reading */
		}
	}
	/* Convert spectral to XYZ */
	if (p->sp2cie != NULL && val.sp.spec_n > 0) {
		p->sp2cie->convert(p->sp2cie, val.XYZ, &val.sp);
		icmClamp3(val.XYZ, val.XYZ);
		val.XYZ_v = 1;
	}

	if (val.XYZ_v == 0) {
		printf("Unexpected failure to get measurement\n");
		return 2;
	}

	a1logd(p->log,1,"Measured ambient of %f\n",val.XYZ[1]);
	if (ambient != NULL)
		*ambient = val.XYZ[1];
	
	/* Configure the instrument mode back to reading the display */
	if ((rv = config_inst_displ(p)) != 0)
		return rv;

	printf("\nPlace the instrument back on the test window\n");
	fflush(stdout);

	return 0;
}


/* Test without a spectrometer using a fake device */
/* Return nz on fail/abort  - see dispsup.h */
/* Use disprd_err() to interpret it */
static int disprd_fake_read(
	disprd *p,
	col *cols,		/* Array of patch colors to be tested */
	int npat, 		/* Number of patches to be tested */
	int spat,		/* Start patch index for "verb", 0 if not used */
	int tpat,		/* Total patch index for "verb", 0 if not used */
	int acr,		/* If nz, do automatic final carriage return */
	int tc,			/* If nz, termination key */
	instClamping clamp	/* NZ if clamp XYZ/Lab to be +ve */
) {
	icmXYZNumber white;		/* White point */
	icmXYZNumber red;		/* Red colorant */
	icmXYZNumber green;		/* Green colorant */
	icmXYZNumber blue;		/* Blue colorant */
	double doff[3];			/* device offsets */
	double mat[3][3];		/* Destination matrix */
	double xmat[3][3];		/* Extra matrix */
	double ooff[3];			/* XYZ offsets */
	double rgb[3];			/* Given test values */
	double crgb[3];			/* Calibrated test values */
//	double br = 35.4;		/* Overall brightness */
	double br = 120.0;		/* Overall brightness */
	int patch, j;
	int ttpat = tpat;
	inst_code (*uicallback)(void *, inst_ui_purp) = NULL;
	void *uicontext = NULL;

	if (ttpat < npat)
		ttpat = npat;

	/* Setup fake device */
	white.X = br * 0.955;		/* Somewhere between D50 and D65 */
	white.Y = br * 1.00;
	white.Z = br * 0.97;
	red.X = br * 0.41;
	red.Y = br * 0.21;
	red.Z = br * 0.02;
	green.X = br * 0.30;
	green.Y = br * 0.55;
	green.Z = br * 0.15;
	blue.X = br * 0.15;
	blue.Y = br * 0.10;
	blue.Z = br * 0.97;
#ifdef SIMPLE_MODEL
	doff[0] = doff[1] = doff[2] = 0.0; /* Input offset */
	ooff[0] = ooff[1] = ooff[2] = 0.0; /* Output offset */
#else
	/* Input offset, equivalent to RGB offsets having various values */
	doff[0] = 0.05;
	doff[1] = 0.06;
	doff[2] = 0.07;
	/* Output offset - equivalent to flare [range 0.0 - 1.0] */
	ooff[0] = 0.03;
	ooff[1] = 0.04;
	ooff[2] = 0.09;
#endif

	if (icmRGBprim2matrix(white, red, green, blue, mat))
		error("Fake read unexpectedly got singular matrix\n");

	icmTranspose3x3(mat, mat);	/* Convert [RGB][XYZ] to [XYZ][RGB] */

	icmSetUnity3x3(xmat);

	if (p->fake2 == 1) {
		/* Target matrix */
		xmat[0][0] = 1.0; xmat[0][1] = 0.01; xmat[0][2] = 0.02;
		xmat[1][0] = 0.1; xmat[1][1] = 1.11; xmat[1][2] = 0.12;
		xmat[2][0] = 0.2; xmat[2][1] = 0.2;  xmat[2][2] = 1.22;
	}

	uicallback = inst_get_uicallback();
	uicontext = inst_get_uicontext();

	/* Setup the keyboard trigger to return our commands */
	inst_set_uih(0x0, 0xff,  DUIH_TRIG);
	inst_set_uih('q', 'q',   DUIH_ABORT);
	inst_set_uih('Q', 'Q',   DUIH_ABORT);
	inst_set_uih(0x03, 0x03, DUIH_ABORT);		/* ^c */
	inst_set_uih(0x1b, 0x1b, DUIH_ABORT);		/* Esc */

	/* Setup user termination character */
	inst_set_uih(tc, tc, DUIH_TERM);

	for (patch = 0; patch < npat; patch++) {
		if (spat != 0 && tpat != 0)
			a1logv(p->log, 1, "%cpatch %d of %d",cr_char,spat+patch,tpat);
		crgb[0] = rgb[0] = cols[patch].r;
		crgb[1] = rgb[1] = cols[patch].g;
		crgb[2] = rgb[2] = cols[patch].b;

		/* deal with a user terminate or abort */
		if (uicallback(uicontext, inst_measuring) == inst_user_abort) {
			int ch, keyc = inst_get_uih_char();

			/* Deal with a user terminate */
			if (keyc & DUIH_TERM) {
				return 4;

			/* Deal with a user abort */
			} else if (keyc & DUIH_ABORT) {
				empty_con_chars();
				printf("\nSample read stopped at user request!\n");
				printf("Hit Esc or Q to give up, any other key to retry:"); fflush(stdout);
				if ((ch = next_con_char()) == 0x1b || ch == 0x3 || ch == 'q' || ch == 'Q') {
					printf("\n");
					return 1;
				}
				printf("\n");
			}
		}

//printf("~1 patch %d RGB %f %f %f\n",patch,rgb[0], rgb[1], rgb[2]);
		/* If we have a calibration, apply it to the color */
		if (p->cal[0][0] >= 0.0) {
			double inputEnt_1 = (double)(p->ncal-1);

			for (j = 0; j < 3; j++) {
				unsigned int ix;
				double val, w;
				val = rgb[j] * inputEnt_1;
				if (val < 0.0) {
					val = 0.0;
				} else if (val > inputEnt_1) {
					val = inputEnt_1;
				}
				ix = (unsigned int)floor(val);		/* Coordinate */
				if (ix > (p->ncal-2))
					ix = (p->ncal-2);
				w = val - (double)ix;		/* weight */
				val = p->cal[j][ix];
				crgb[j] = val + w * (p->cal[j][ix+1] - val);
			}
//printf("~1 patch %d cal RGB %f %f %f\n",patch, crgb[0], crgb[1], crgb[2]);
		}

		/* If we have a test window, display the patch color */
		if (p->dw) {
			inst_code rv;
			if (p->native & 1) {	/* Apply soft calibration to display value */
				if ((rv = p->dw->set_color(p->dw, crgb[0], crgb[1], crgb[2])) != 0) {
					a1logd(p->log,1,"set_color() returned %d\n",rv);
					return 3;
				}
			} else {			/* Hardware will apply calibration */
				if ((rv = p->dw->set_color(p->dw, rgb[0], rgb[1], rgb[2])) != 0) {
					a1logd(p->log,1,"set_color() returned %d\n",rv);
					return 3;
				}
			}
		}

		/* Apply the fake devices level of quantization */
#ifdef FAKE_BITS
		if (p->fake2 == 0) {
			for (j = 0; j < 3; j++) {
				int vv;
				vv = (int) (crgb[j] * ((1 << FAKE_BITS) - 1.0) + 0.5);
				crgb[j] =  vv/((1 << FAKE_BITS) - 1.0);
			}
		}
#endif

		/* Apply device offset */
		for (j = 0; j < 3; j++) {
			if (crgb[j] < 0.0)
				crgb[j] = 0.0;
			else if (crgb[j] > 1.0)
				crgb[j] = 1.0;
			crgb[j] = doff[j] + (1.0 - doff[j]) * crgb[j];
		}

		/* Apply gamma */
		for (j = 0; j < 3; j++) {
			if (crgb[j] >= 0.0)
				crgb[j] = pow(crgb[j], 2.5);
			else
				crgb[j] = 0.0;
		}

		/* Convert to XYZ */
		icmMulBy3x3(cols[patch].XYZ, mat, crgb);

		/* Apply XYZ offset */
		for (j = 0; j < 3; j++)
			cols[patch].XYZ[j] += ooff[j];

		/* Apply extra matrix */
		icmMulBy3x3(cols[patch].XYZ, xmat, cols[patch].XYZ);

#ifdef FAKE_NOISE
		if (p->fake2 == 0) {
			cols[patch].XYZ[0] += 2.0 * FAKE_NOISE * d_rand(-1.0, 1.0);
			cols[patch].XYZ[1] += FAKE_NOISE * d_rand(-1.0, 1.0);
			cols[patch].XYZ[2] += 4.0 * FAKE_NOISE * d_rand(-1.0, 1.0);
		}
#endif
		if (clamp)
			icmClamp3(cols[patch].XYZ, cols[patch].XYZ);
//printf("~1 patch %d XYZ %f %f %f\n",patch,cols[patch].XYZ[0], cols[patch].XYZ[1], cols[patch].XYZ[2]);
		cols[patch].XYZ_v = 1;
		cols[patch].sp.spec_n = 0;
		cols[patch].mtype = inst_mrt_emission;
	}
	if (acr && spat != 0 && tpat != 0 && (spat+patch-1) == tpat)
		a1logv(p->log, 1, "\n");
	return 0;
}

/* Test without a spectrometer using a fake ICC profile device */
/* Return nz on fail/abort - see dispsup.h */
/* Use disprd_err() to interpret it */
static int disprd_fake_read_lu(
	disprd *p,
	col *cols,		/* Array of patch colors to be tested */
	int npat, 		/* Number of patches to be tested */
	int spat,		/* Start patch index for "verb", 0 if not used */
	int tpat,		/* Total patch index for "verb", 0 if not used */
	int acr,		/* If nz, do automatic final carriage return */
	int tc,			/* If nz, termination key */
	instClamping clamp	/* NZ if clamp XYZ/Lab to be +ve */
) {
	int patch, j;
	int ttpat = tpat;
	double br = 120.4;		/* Overall brightness */
	inst_code (*uicallback)(void *, inst_ui_purp) = NULL;
	void *uicontext = NULL;

	if (ttpat < npat)
		ttpat = npat;

	uicallback = inst_get_uicallback();
	uicontext = inst_get_uicontext();

	/* Setup the keyboard trigger to return our commands */
	inst_set_uih(0x0, 0xff,  DUIH_TRIG);
	inst_set_uih('q', 'q',   DUIH_ABORT);
	inst_set_uih('Q', 'Q',   DUIH_ABORT);
	inst_set_uih(0x03, 0x03, DUIH_ABORT);		/* ^c */
	inst_set_uih(0x1b, 0x1b, DUIH_ABORT);		/* Esc */

	/* Setup user termination character */
	inst_set_uih(tc, tc, DUIH_TERM);

	for (patch = 0; patch < npat; patch++) {
		double rgb[3];;
		if (spat != 0 && tpat != 0)
			a1logv(p->log, 1, "%cpatch %d of %d",cr_char,spat+patch,tpat);
		rgb[0] = cols[patch].r;
		rgb[1] = cols[patch].g;
		rgb[2] = cols[patch].b;

		/* deal with a user terminate or abort */
		if (uicallback(uicontext, inst_measuring) == inst_user_abort) {
			int ch, keyc = inst_get_uih_char();

			/* Deal with a user terminate */
			if (keyc & DUIH_TERM) {
				return 4;

			/* Deal with a user abort */
			} else if (keyc & DUIH_ABORT) {
				empty_con_chars();
				printf("\nSample read stopped at user request!\n");
				printf("Hit Esc or Q to give up, any other key to retry:"); fflush(stdout);
				if ((ch = next_con_char()) == 0x1b || ch == 0x3 || ch == 'q' || ch == 'Q') {
					printf("\n");
					return 1;
				}
				printf("\n");
			}
		}

		/* If we have a test window, display the patch color */
		if (p->dw) {
			inst_code rv;
			if ((rv = p->dw->set_color(p->dw, rgb[0], rgb[1], rgb[2])) != 0) {
				a1logd(p->log,1,"set_color() returned %d\n",rv);
				return 3;
			}
		}

		/* If we have a RAMDAC, apply it to the color */
		if (p->cal[0][0] >= 0.0) {
			double inputEnt_1 = (double)(p->ncal-1);

			for (j = 0; j < 3; j++) {
				unsigned int ix;
				double val, w;

				val = rgb[j] * inputEnt_1;
				if (val < 0.0) {
					val = 0.0;
				} else if (val > inputEnt_1) {
					val = inputEnt_1;
				}
				ix = (unsigned int)floor(val);		/* Coordinate */
				if (ix > (p->ncal-2))
					ix = (p->ncal-2);
				w = val - (double)ix;		/* weight */
				val = p->cal[j][ix];
				rgb[j] = val + w * (p->cal[j][ix+1] - val);
			}
		}

		p->fake_lu->lookup(p->fake_lu, cols[patch].XYZ, rgb); 
		for (j = 0; j < 3; j++) 
			cols[patch].XYZ[j] *= br;
#ifdef FAKE_NOISE
		cols[patch].XYZ[0] += 2.0 * FAKE_NOISE * d_rand(-1.0, 1.0);
		cols[patch].XYZ[1] += FAKE_NOISE * d_rand(-1.0, 1.0);
		cols[patch].XYZ[2] += 4.0 * FAKE_NOISE * d_rand(-1.0, 1.0);
#endif
		if (clamp)
			icmClamp3(cols[patch].XYZ, cols[patch].XYZ);
		cols[patch].XYZ_v = 1;
		cols[patch].sp.spec_n = 0;
		cols[patch].mtype = inst_mrt_emission;
	}
	if (acr && spat != 0 && tpat != 0 && (spat+patch-1) == tpat)
		a1logv(p->log, 1, "\n");
	return 0;
}

/* Use without a direct connect spectrometer using shell callout */
/* Return nz on fail/abort - see duspsup.h */
/* Use disprd_err() to interpret it */
static int disprd_fake_read_co(disprd *p,
	col *cols,		/* Array of patch colors to be tested */
	int npat, 		/* Number of patches to be tested */
	int spat,		/* Start patch index for "verb", 0 if not used */
	int tpat,		/* Total patch index for "verb", 0 if not used */
	int acr,		/* If nz, do automatic final carriage return */
	int tc,			/* If nz, termination key */
	instClamping clamp	/* NZ if clamp XYZ/Lab to be +ve */
) {
	int patch, j;
	int ttpat = tpat;
	inst_code (*uicallback)(void *, inst_ui_purp) = NULL;
	void *uicontext = NULL;

	if (ttpat < npat)
		ttpat = npat;

	uicallback = inst_get_uicallback();
	uicontext = inst_get_uicontext();

	/* Setup the keyboard trigger to return our commands */
	inst_set_uih(0x0, 0xff,  DUIH_TRIG);
	inst_set_uih('q', 'q',   DUIH_ABORT);
	inst_set_uih('Q', 'Q',   DUIH_ABORT);
	inst_set_uih(0x03, 0x03, DUIH_ABORT);		/* ^c */
	inst_set_uih(0x1b, 0x1b, DUIH_ABORT);		/* Esc */

	/* Setup user termination character */
	inst_set_uih(tc, tc, DUIH_TERM);

	for (patch = 0; patch < npat; patch++) {
		double rgb[3];
		int rv;
		char *cmd;
		FILE *fp;

		/* deal with a user terminate or abort */
		if (uicallback(uicontext, inst_measuring) == inst_user_abort) {
			int ch, keyc = inst_get_uih_char();

			/* Deal with a user terminate */
			if (keyc & DUIH_TERM) {
				return 4;

			/* Deal with a user abort */
			} else if (keyc & DUIH_ABORT) {
				empty_con_chars();
				printf("\nSample read stopped at user request!\n");
				printf("Hit Esc or Q to give up, any other key to retry:"); fflush(stdout);
				if ((ch = next_con_char()) == 0x1b || ch == 0x3 || ch == 'q' || ch == 'Q') {
					printf("\n");
					return 1;
				}
				printf("\n");
			}
		}

		if (spat != 0 && tpat != 0)
			a1logv(p->log, 1, "%cpatch %d of %d",cr_char,spat+patch,tpat);
		rgb[0] = cols[patch].r;
		rgb[1] = cols[patch].g;
		rgb[2] = cols[patch].b;

		/* If we have a test window, display the patch color */
		if (p->dw) {
			inst_code rv;
			if ((rv = p->dw->set_color(p->dw, rgb[0], rgb[1], rgb[2])) != 0) {
				a1logd(p->log,1,"set_color() returned %d\n",rv);
				return 3;
			}
		}

		/* If we have a RAMDAC, apply it to the color */
		if (p->cal[0][0] >= 0.0) {
			double inputEnt_1 = (double)(p->ncal-1);

			for (j = 0; j < 3; j++) {
				unsigned int ix;
				double val, w;

				val = rgb[j] * inputEnt_1;
				if (val < 0.0) {
					val = 0.0;
				} else if (val > inputEnt_1) {
					val = inputEnt_1;
				}
				ix = (unsigned int)floor(val);		/* Coordinate */
				if (ix > (p->ncal-2))
					ix = (p->ncal-2);
				w = val - (double)ix;		/* weight */
				val = p->cal[j][ix];
				rgb[j] = val + w * (p->cal[j][ix+1] - val);
			}
		}

		if ((cmd = malloc(strlen(p->mcallout) + 200)) == NULL)
			error("Malloc of command string failed");

		sprintf(cmd, "%s %d %d %d %f %f %f",p->mcallout,
			        (int)(rgb[0] * 255.0 + 0.5),
		            (int)(rgb[1] * 255.0 + 0.5),
		            (int)(rgb[2] * 255.0 + 0.5), rgb[0], rgb[1], rgb[2]);
		if ((rv = system(cmd)) != 0)
			error("System command '%s' failed with %d",cmd,rv); 

		/* Now read the XYZ result from the mcallout.meas file */
		sprintf(cmd, "%s.meas",p->mcallout);
		if ((fp = fopen(cmd,"r")) == NULL)
			error("Unable to open measurement value file '%s'",cmd);

		if (fscanf(fp, " %lf %lf %lf", &cols[patch].XYZ[0], &cols[patch].XYZ[1],
		                               &cols[patch].XYZ[2]) != 3)
			error("Unable to parse measurement value file '%s'",cmd);
		fclose(fp);
		free(cmd);

		if (clamp)
			icmClamp3(cols[patch].XYZ, cols[patch].XYZ);
		cols[patch].XYZ_v = 1;
		cols[patch].mtype = inst_mrt_emission;

		a1logv(p->log, 2, "Read XYZ %f %f %f from '%s'\n", cols[patch].XYZ[0],
			                     cols[patch].XYZ[1],cols[patch].XYZ[2], cmd);

	}
	if (acr && spat != 0 && tpat != 0 && (spat+patch-1) == tpat)
		a1logv(p->log, 1, "\n");
	return 0;
}

/* Return a string describing the error code */
char *disprd_err(int en) {
	switch(en) {
		case 1:
			return "User Aborted";
		case 2:
			return "Instrument Access Failed";
		case 22:
			return "Instrument Access Failed (No PLD Pattern - have you run oeminst ?)";
		case 3:
			return "Window Access Failed";
		case 4:
			return "VideoLUT Access Failed";
		case 5:
			return "User Terminated";
		case 6:
			return "System Error";
		case 7:
			return "Either CRT or LCD must be selected";
		case 8:
			return "Instrument has no ambient measurement capability";
		case 9:
			return "Creating spectral conversion object failed";
		case 10:
			return "Instrument has no CCMX capability";
		case 11:
			return "Instrument has no CCSS capability";
		case 12:
			return "Video encoding requested using nonlinear current calibration curves";
		case 13:
			return "Video encoding requested for MadVR display - use MadVR to set video encoding";
		case 14:
			return "Instrument has no set refresh rate capability";
		case 15:
			return "Unknown calibration display type selection";
		case 16:
			return "Must use BASE calibration display type selection";
	}
	return "Unknown";
}

static void disprd_del(disprd *p) {

	if (p->log->verb >= 1 && p->bdrift && p->ref_bw_v && p->last_bw_v) {
		icmXYZNumber w;
		double de;
		icmAry2XYZ(w, p->ref_bw[1].XYZ);
		de = icmXYZLabDE(&w, p->ref_bw[0].XYZ, p->last_bw[0].XYZ);
		a1logv(p->log, 1, "Black drift was %f DE\n",de);
	}
	if (p->log->verb >= 1 && p->wdrift && p->ref_bw_v && p->last_bw_v) {
		icmXYZNumber w;
		double de;
		icmAry2XYZ(w, p->ref_bw[1].XYZ);
		de = icmXYZLabDE(&w, p->ref_bw[1].XYZ, p->last_bw[1].XYZ);
		a1logv(p->log, 1, "White drift was %f DE\n",de);
	}

	/* The user may remove the instrument */
	if (p->dw != NULL)
		printf("The instrument can be removed from the screen.\n");

	if (p->fake_lu != NULL)
		p->fake_lu->del(p->fake_lu);
	if (p->fake_icc != NULL)
		p->fake_icc->del(p->fake_icc);
	if (p->fake_fp != NULL)
		p->fake_fp->del(p->fake_fp);

	if (p->it != NULL)
		p->it->del(p->it);
	if (p->dw != NULL) {
		p->dw->del(p->dw);
	}
	if (p->sp2cie != NULL)
		p->sp2cie->del(p->sp2cie); 
	p->log = del_a1log(p->log);
	free(p);
}

/* Helper to configure the instrument mode ready */
/* for reading the display */
/* return new_disprd() error code */
static int config_inst_displ(disprd *p) {
	inst_mode cap;
	inst2_capability cap2;
	inst3_capability cap3;
	inst_mode mode = 0;
	int rv;
	
	p->it->capabilities(p->it, &cap, &cap2, &cap3);
	
	if (p->tele && !IMODETST(cap, inst_mode_emis_tele)) {
		printf("Want telephoto measurement capability but instrument doesn't support it\n");
		printf("so falling back to spot mode.\n");
		a1logd(p->log,1,"No telephoto mode so falling back to spot mode.\n");
		p->tele = 0;
	}
	
	if (!p->tele && !IMODETST(cap, inst_mode_emis_spot)) {
		printf("Want emissive spot measurement capability but instrument doesn't support it\n");
		printf("so switching to telephoto spot mode.\n");
		p->tele = 1;
	}
	
	if (( p->tele && !IMODETST(cap, inst_mode_emis_tele))
	 || (!p->tele && !IMODETST(cap, inst_mode_emis_spot))) {
		printf("Need %s emissive measurement capability,\n", p->tele ? "telephoto" : "spot");
		printf("but instrument doesn't support it\n");
		a1logd(p->log,1,"Need %s emissive measurement capability but device doesn't support it,\n",
		       p->tele ? "telephoto" : "spot");
		return 2;
	}
	
	if (p->nadaptive && !IMODETST(cap, inst_mode_emis_nonadaptive)) {
		printf("Need non-adaptives measurement mode, but instrument doesn't support it\n");
		a1logd(p->log,1, "Need non-adaptives measurement mode, but instrument doesn't support it\n");
		return 2;
	}
	
	if (p->obType != icxOT_none
	 && p->obType != icxOT_default) {
		if (!IMODETST(cap, inst_mode_spectral) && (cap2 & inst2_ccss) == 0) {
			printf("A non-standard observer was requested,\n");
			printf("but instrument doesn't support spectral or CCSS\n");
			a1logd(p->log,1,"A non-standard observer was requested,\n"
			          "but instrument doesn't support spectral or CCSS\n");
			return 2;
		}
		/* Make sure spectral is turned on if an observer is requested */
		if (!p->spectral && (cap2 & inst2_ccss) == 0)
			p->spectral = 1;
	}

	if (p->spectral && !IMODETST(cap,inst_mode_spectral)) {
		if (p->spectral != 2) {		/* Not soft */
			printf("Spectral information was requested,\n");
			printf("but instrument doesn't support it\n");
			a1logd(p->log,1,"Spectral information was requested,\nbut instrument doesn't support it\n");
			return 2;
		}
		p->spectral = 0;
	}
	
	if (p->tele) {
		mode = inst_mode_emis_tele;
	} else {
		mode = inst_mode_emis_spot;
	}
	if (p->nadaptive)
		mode |= inst_mode_emis_nonadaptive;
	
	if (p->spectral) {
		mode |= inst_mode_spectral;
		p->spectral = 1;
	} else {
		p->spectral = 0;
	}
	
	/* Set the display type */
	if (p->dtype != 0) {
		if (cap2 & inst2_disptype) {
			int ix;
			if ((ix = inst_get_disptype_index(p->it, p->dtype, p->docbid)) < 0) {
				a1logd(p->log,1,"Display type selection '%c' is not valid for instrument\n",p->dtype);
				if (p->docbid)
					return 16;
				return 15;
			}
			if ((rv = p->it->set_disptype(p->it, ix)) != inst_ok) {
				a1logd(p->log,1,"Setting display type failed with '%s' (%s)\n",
				       p->it->inst_interp_error(p->it, rv), p->it->interp_error(p->it, rv));
				return 15;
			}
		} else
			printf("Display type ignored - instrument doesn't support display type\n");
	}

	/* Get the refresh mode and cbid */
	if (cap2 & inst2_disptype) {
		p->it->get_set_opt(p->it, inst_opt_get_dtinfo, &p->refrmode, &p->cbid);
	}
	
	/* Disable initcalibration of machine if selected */
	if (p->noinitcal != 0) {
		if ((rv = p->it->get_set_opt(p->it,inst_opt_noinitcalib, 0)) != inst_ok) {
			a1logd(p->log,1,"Setting no-initial calibrate failed failed with '%s' (%s)\n",
		       p->it->inst_interp_error(p->it, rv), p->it->interp_error(p->it, rv));
			printf("Disable initial-calibrate not supported\n");
		}
	}
	
	if (p->highres) {
		if (IMODETST(cap, inst_mode_highres)) {
			mode |= inst_mode_highres;
		} else {
			a1logv(p->log, 1, "high resolution ignored - instrument doesn't support high res. mode\n");
		}
	}
	if ((rv = p->it->set_mode(p->it, mode)) != inst_ok) {
		a1logd(p->log,1,"set_mode returned '%s' (%s)\n",
		       p->it->inst_interp_error(p->it, rv), p->it->interp_error(p->it, rv));
		return 2;
	}
	p->it->capabilities(p->it, &cap, &cap2, &cap3);

	if (p->ccmtx != NULL) {
		if ((cap2 & inst2_ccmx) == 0) {
			a1logd(p->log,1,"Instrument doesn't support ccmx correction\n");
			return 10;
		}
		if ((rv = p->it->col_cor_mat(p->it, p->ccmtx)) != inst_ok) {
			a1logd(p->log,1,"col_cor_mat returned '%s' (%s)\n",
			       p->it->inst_interp_error(p->it, rv), p->it->interp_error(p->it, rv));
			return 2;
		}
	}
	
	/* Observer */
	if ((cap2 & inst2_ccss) != 0 && p->obType != icxOT_default) {

		if ((cap2 & inst2_ccss) == 0) {
			a1logd(p->log,1,"Instrument doesn't support ccss calibration and we need it\n");
			return 11;
		}
		if ((rv = p->it->get_set_opt(p->it, inst_opt_set_ccss_obs, p->obType, p->custObserver))
			                                                                      != inst_ok) {
			a1logd(p->log,1,"inst_opt_set_ccss_obs returned '%s' (%s)\n",
			       p->it->inst_interp_error(p->it, rv), p->it->interp_error(p->it, rv));
			return 2;
		}
	}

	/* Custom CCSS */
	if (p->sets != NULL) {

		if ((cap2 & inst2_ccss) == 0) {
			a1logd(p->log,1,"Instrument doesn't support ccss calibration and we need it\n");
			return 11;
		}

		if ((rv = p->it->col_cal_spec_set(p->it, p->sets, p->no_sets)) != inst_ok) {
			a1logd(p->log,1,"col_cal_spec_set returned '%s' (%s)\n",
			       p->it->inst_interp_error(p->it, rv), p->it->interp_error(p->it, rv));
			return 2;
		}
	}
	
	if (p->refrate > 0.0) {
		if (!(cap2 & inst2_set_refresh_rate)) {
			a1logd(p->log,1,"Instrument doesn't support setting refresh rate\n");
			return 11;
		} else {
			if ((rv = p->it->set_refr_rate(p->it, p->refrate)) != inst_ok) {
				a1logd(p->log,1,"set_refr_rate %f Hz returned '%s' (%s)\n",
			     p->refrate, p->it->inst_interp_error(p->it, rv), p->it->interp_error(p->it, rv));
				return 2;
			}
		}
	}

	/* Set the trigger mode to program triggered */
	if ((rv = p->it->get_set_opt(p->it,inst_opt_trig_prog)) != inst_ok) {
		a1logd(p->log,1,"Setting program trigger mode failed failed with '%s' (%s)\n",
	       p->it->inst_interp_error(p->it, rv), p->it->interp_error(p->it, rv));
		return 2;
	}

	/* Reset key meanings */
	inst_reset_uih();

	a1logd(p->log,1,"config_inst_displ suceeded\n");
	return 0;
}

/* Create a display reading object. */
/* Return NULL if error */
/* Set *errc to code. See dispsup.h */
/* Use disprd_err() to interpret *errc */
disprd *new_disprd(
int *errc,          /* Error code. May be NULL (could use log for this instead?) */
icompath *ipath,	/* Instrument path to open, &icomFakeDevice == fake */
flow_control fc,	/* Flow control */
int dtype,			/* Display type selection character */
int docbid,			/* NZ to only allow cbid dtypes */
int tele,			/* NZ for tele mode. Falls back to display mode */
int nadaptive,		/* NZ for non-adaptive mode */
int noinitcal,		/* No initial instrument calibration */
int noinitplace,	/* Don't wait for user to place instrument on screen */
int highres,		/* Use high res mode if available */
double refrate,		/* If != 0.0, set display refresh rate calibration */
int native,			/* X0 = use current per channel calibration curve */
					/* X1 = set native linear output and use ramdac high precn. */
					/* 0X = use current color management cLut (MadVR) */
					/* 1X = disable color management cLUT (MadVR) */
int *noramdac,		/* Return nz if no ramdac access. native is set to X0 */
int *nocm,			/* Return nz if no CM cLUT access. native is set to 0X */
double cal[3][MAX_CAL_ENT],	/* Calibration (cal == NULL or cal[0][0] < 0.0 if not valid) */
int ncal,			/* Number of cal[] entries */
disppath *disp,		/* Display to calibrate. NULL if fake and no dispwin */
int out_tvenc,		/* 1 = use RGB Video Level encoding */
int blackbg,		/* NZ if whole screen should be filled with black */
int override,		/* Override_redirect on X11 */
int webdisp,        /* If nz, port number for web color display */
#ifdef NT
int madvrdisp,		/* NZ for MadVR display */
#endif
char *ccallout,		/* Shell callout on set color */
char *mcallout,		/* Shell callout on measure color (forced fake) */
double hpatsize,	/* Size of dispwin */
double vpatsize,
double ho,			/* Horizontal offset */
double vo,			/* Vertical offset */
double ccmtx[3][3],	/* Colorimeter Correction matrix, NULL if none */
xspect *sets,		/* CCSS Set of sample spectra, NULL if none  */
int no_sets,	 	/* CCSS Number on set, 0 if none */
int spectral,		/* Generate spectral info flag */
icxObserverType obType,	/* Use alternate observer if spectral or CCSS and != icxOT_none */
xspect custObserver[3],	/* Optional custom observer */
int bdrift,			/* Flag, nz for black drift compensation */
int wdrift,			/* Flag, nz for white drift compensation */
char *fake_name,	/* Name of profile to use as a fake device */
a1log *log      	/* Verb, debug & error log */
) {
	disprd *p = NULL;
	int ch;
	inst_code rv;
	int uout_tvenc = out_tvenc;			/* tvenc to use with dispwin value setting */

	if (errc != NULL) *errc = 0;		/* default return code = no error */

	/* Allocate a disprd */
	if ((p = (disprd *)calloc(sizeof(disprd), 1)) == NULL) {
		a1logd(log, 1, "new_disprd failed due to malloc failure\n");
		if (errc != NULL) *errc = 6;
		return NULL;
	}
	p->log = new_a1log_d(log);
	p->del = disprd_del;
	p->read = disprd_read;
	p->get_disptype = disprd_get_disptype;
	p->reset_targ_w = disprd_reset_targ_w;
	p->change_drift_comp = disprd_change_drift_comp;
	p->ambient = disprd_ambient;
	p->fake_name = fake_name;

	p->ccmtx = ccmtx;
	p->sets = sets;
	p->no_sets = no_sets;		/* CCSS */
	p->spectral = spectral;
	p->obType = obType;			/* CCSS or spectral */
	p->custObserver = custObserver;
	p->bdrift = bdrift;
	p->wdrift = wdrift;
	p->dtype = dtype;
	p->docbid = docbid;
	p->refrmode = -1;			/* Unknown */
	p->cbid = 0;				/* Unknown */
	p->tele = tele;
	p->nadaptive = nadaptive;
	p->noinitcal = noinitcal;
	p->noinitplace = noinitplace;
	p->highres = highres;
	p->refrate = refrate;
	if (mcallout != NULL)
		ipath = &icomFakeDevice;	/* Force fake device */
	p->mcallout = mcallout;
	p->ipath = ipath;
	p->br = baud_19200;
	p->fc = fc;

	p->native = native;

#ifdef FAKE_NOISE 
# ifdef FAKE_UNPREDIC
	rand32(time(NULL));
# endif
#endif

	/* Save this so we can return current cal, or */
	/* in case we are using a fake device */
	if (cal != NULL && cal[0][0] >= 0.0) {
		int j, i;
		for (j = 0; j < 3; j++) {
			for (i = 0; i < ncal; i++) {
				p->cal[j][i] = cal[j][i];
			}
		}
		p->ncal = ncal;
	} else {
		p->cal[0][0] =  -1.0;
		p->ncal = 0;
	}

	/* If non-real instrument */
	if (ipath == &icomFakeDevice) {
		p->fake = 1;

		p->fake_fp = NULL;
		p->fake_icc = NULL;
		p->fake_lu = NULL;

		/* See if there is a profile we should use as the fake device */
		if (p->mcallout == NULL && p->fake_name != NULL
		 && (p->fake_fp = new_icmFileStd_name(p->fake_name,"r")) != NULL) {
			if ((p->fake_icc = new_icc()) != NULL) {
				if (p->fake_icc->read(p->fake_icc,p->fake_fp,0) == 0) {
					icColorSpaceSignature ins;
					p->fake_lu = p->fake_icc->get_luobj(p->fake_icc, icmFwd, icAbsoluteColorimetric,
					                            icSigXYZData, icmLuOrdNorm);
					p->fake_lu->spaces(p->fake_lu, &ins, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
					if (ins != icSigRgbData) {
						p->fake_lu->del(p->fake_lu);
						p->fake_lu = NULL;
					}
				}
			}
		}

		if (p->fake_lu != NULL) {
			a1logv(p->log, 1, "Using profile '%s' rather than real device\n",p->fake_name);
			p->read = disprd_fake_read_lu;
		} else if (p->mcallout != NULL) {
			a1logv(p->log, 1, "Using shell callout '%s' rather than real device\n",p->mcallout);
			p->read = disprd_fake_read_co;
		} else
			p->read = disprd_fake_read;

		if (disp == NULL) {
			a1logd(log,1,"new_disprd returning fake device\n");
			return p;
		}

	/* Setup the instrument */
	} else {
	
		a1logv(p->log, 1, "Setting up the instrument\n");
	
		if ((p->it = new_inst(ipath, 0, log, DUIH_FUNC_AND_CONTEXT)) == NULL) {
			a1logd(p->log,1,"new_disprd failed because new_inst failed\n");
			p->del(p);
			if (errc != NULL) *errc = 2;
			return NULL;
		}
	
		/* Establish communications */
		if ((rv = p->it->init_coms(p->it, p->br, p->fc, 15.0)) != inst_ok) {
			a1logd(log,1,"init_coms returned '%s' (%s)\n",
			       p->it->inst_interp_error(p->it, rv), p->it->interp_error(p->it, rv));
			a1logd(log,1,"new_disprd failed because init_coms failed\n");
			p->del(p);
			if (errc != NULL) *errc = 2;
			return NULL;
		}
	
		/* Initialise the instrument */
		if ((rv = p->it->init_inst(p->it)) != inst_ok) {
			a1logd(log,1,"init_inst returned '%s' (%s)\n",
			       p->it->inst_interp_error(p->it, rv), p->it->interp_error(p->it, rv));
			a1logd(log,1,"new_disprd failed because init_inst failed\n");
			p->del(p);
			if (errc != NULL) {
				*errc = 2;
				if ((rv & inst_imask) == SPYD2_NO_PLD_PATTERN)
					*errc = 22;
			}
			return NULL;
		}
	
		/* Configure the instrument mode for reading the display */
		if ((rv = config_inst_displ(p)) != 0) {
			a1logd(log,1,"new_disprd failed because config_inst_displ failed\n");
			p->del(p);
			if (errc != NULL) *errc = rv;
			return NULL;
		}
	}

	/* Create a spectral conversion object if needed */
	if (p->spectral && p->obType != icxOT_none) {
		if ((p->sp2cie = new_xsp2cie(icxIT_none, NULL, p->obType, custObserver, icSigXYZData, icxNoClamp))
		                                                                                 == NULL) {
			a1logd(log,1,"new_disprd failed because creation of spectral conversion object failed\n");
			p->del(p);
			if (errc != NULL) *errc = 9;
			return NULL;
		}
	}

	if (webdisp != 0) {
		/* Open web display */
		if ((p->dw = new_webwin(webdisp, hpatsize, vpatsize, ho, vo, 0, native, noramdac, nocm,
			                    uout_tvenc, 0, p->log->verb, p->log->debug)) == NULL) {
			a1logd(log,1,"new_disprd failed because new_webwin failed\n");
			p->del(p);
			if (errc != NULL) *errc = 3;
			return NULL;
		}
#ifdef NT
	} else if (madvrdisp != 0) {
		if (out_tvenc) {
			a1logd(log,1,"new_disprd failed because tv_enc & MadVR window\n");
			p->del(p);
			if (errc != NULL) *errc = 13;
			return NULL;
		}
			
		if ((p->dw = new_madvrwin(hpatsize, vpatsize, ho, vo, 0, native, noramdac, nocm, out_tvenc,
			                                  blackbg, p->log->verb, p->log->debug)) == NULL) {
			a1logd(log,1,"new_disprd failed because new_madvrwin failed\n");
			p->del(p);
			if (errc != NULL) *errc = 3;
			return NULL;
		}
#endif
	} else {
		/* Don't do tvenc on test values if we are going to do it with RAMDAC curve */
		if (out_tvenc && (p->native & 1) == 0 && p->cal[0][0] >= 0.0) {
			uout_tvenc = 0;
		}

		/* Open display window for positioning (no blackbg) */
		if ((p->dw = new_dispwin(disp, hpatsize, vpatsize, ho, vo, 0, native, noramdac, nocm,
			                               uout_tvenc, 0, override, p->log->debug)) == NULL) {
			a1logd(log,1,"new_disprd failed because new_dispwin failed\n");
			p->del(p);
			if (errc != NULL) *errc = 3;
			return NULL;
		}

		/* If TV encoding using existing RAMDAC and it is not linear, */
		/* error out, as TV encoding probably won't work properly. */
		if (out_tvenc && (native & 1) == 0 && p->cal[0][0] < 0.0) {
			ramdac *cr;
			if ((cr = p->dw->get_ramdac(p->dw)) != NULL) {
				int i, j;
				for (i = 0; i < cr->nent; i++) {
					double val = i/(cr->nent-1.0);
					for (j = 0; j < 3; j++) {
						if (fabs(val - cr->v[j][i]) > 1e-5)
							break;
					}
					if (j < 3)
						break;
				}
				if (i < cr->nent) {
					a1logd(log,1,"new_disprd failed because tvenc and nonlinear RAMDAC");
					cr->del(cr);
					p->del(p);
					if (errc != NULL) *errc = 12;
					return NULL;
				}
				cr->del(cr);
			}
		}

#ifdef NEVER		// Don't do this - dispread doesn't save calibration when using existing.
		/* If using exiting RAMDAC, return it */
		if ((native & 1) == 0 && p->cal[0][0] < 0.0 && cal != NULL) {
			ramdac *r;
			
			if ((r = p->dw->get_ramdac(p->dw)) != NULL) {
				int j, i;

				/* Get the ramdac contents. */
				/* We linearly interpolate from RAMDAC[nent] to cal[ncal] resolution */
				for (i = 0; i < ncal; i++) {
					double val, w;
					unsigned int ix;
	
					val = (r->nent-1.0) * i/(ncal-1.0);
					ix = (unsigned int)floor(val);		/* Coordinate */
					if (ix > (r->nent-2))
						ix = (r->nent-2);
					w = val - (double)ix;		/* weight */
					for (j = 0; j < 3; j++) {
						val = r->v[j][ix];
						cal[j][i] = val + w * (r->v[j][ix+1] - val);
					}
				}
				r->del(r);
			}
		}
#endif
	}

	if (p->it != NULL) {
		/* Do an instrument calibration up front, so as not to get in the users way, */
		/* but ignore a CRT frequency or display integration calibration, */
		/* since these will be done automatically. */
		if (p->it->needs_calibration(p->it) & inst_calt_n_dfrble_mask) {
			disp_win_info dwi;
			dwi.dw = p->dw;		/* Set window to use */
	
			rv = inst_handle_calibrate(p->it, inst_calt_needed, inst_calc_none,
			                                  setup_display_calibrate, &dwi);
			setup_display_calibrate(p->it,inst_calc_none, &dwi); 
			printf("\n");
			if (rv != inst_ok) {	/* Abort or fatal error */
				a1logd(log,1,"new_disprd failed because calibrate failed with '%s' (%s)\n",
				       p->it->inst_interp_error(p->it, rv), p->it->interp_error(p->it, rv));
				printf("Calibrate failed with '%s' (%s)\n",
				       p->it->inst_interp_error(p->it, rv), p->it->interp_error(p->it, rv));
				p->del(p);
				if (errc != NULL) *errc = 2;
				return NULL;
			}
		}
	}

	if (!p->noinitplace) {
		inst2_capability cap2;

		p->it->capabilities(p->it, NULL, &cap2, NULL);

		/* Turn target on */
		if (cap2 & inst2_has_target)
			p->it->get_set_opt(p->it, inst_opt_set_target_state, 1);

		/* Ask user to put instrument on screen */
		empty_con_chars();

		printf("Place instrument on test window.\n");
		printf("Hit Esc or Q to give up, any other key to continue:"); fflush(stdout);
		if ((ch = next_con_char()) == 0x1b || ch == 0x3 || ch == 'q' || ch == 'Q') {
			printf("\n");
			a1logd(log,1,"new_disprd failed because user aborted when placing device\n");
			if (cap2 & inst2_has_target) /* Turn target off */
				p->it->get_set_opt(p->it, inst_opt_set_target_state, 0);
			p->del(p);
			if (errc != NULL) *errc = 1;
			return NULL;
		}

		/* Turn target off */
		if (cap2 & inst2_has_target)
			p->it->get_set_opt(p->it, inst_opt_set_target_state, 0);

		printf("\n");
	}

	if (webdisp == 0
#ifdef NT
	 && madvrdisp == 0
#endif
	) {
		/* Close the positioning window */
		if (p->dw != NULL) {
			p->dw->del(p->dw);
		}
	
		/* Open display window again for measurement */
		if ((p->dw = new_dispwin(disp, hpatsize, vpatsize, ho, vo, 0, native, noramdac, nocm,
			                     uout_tvenc, blackbg, override, p->log->debug)) == NULL) {
			a1logd(log,1,"new_disprd failed new_dispwin failed\n");
			p->del(p);
			if (errc != NULL) *errc = 3;
			return NULL;
		}
	}

	/* Set color change callout */
	if (ccallout) {
		p->dw->set_callout(p->dw, ccallout);
	}

	/* If we have a calibration to set using the RAMDAC */
	/* (This is only typically the case for disread) */
	if ((p->native & 1) == 0 && p->cal[0][0] >= 0.0) {

		/* Save current RAMDAC so that we can restore it */
		if (p->dw->r == NULL) {
			warning("Unable to read or set display RAMDAC - switching to softcal");
			p->native |= 1;

		/* Set the given RAMDAC so we can characterise through it */
		} else {
			int j, i;
			
			/* Set the ramdac contents. */
			/* We linearly interpolate from cal[ncal] to RAMDAC[nent] resolution */
			for (i = 0; i < p->dw->r->nent; i++) {
				double val, w;
				unsigned int ix;

				val = (ncal-1.0) * i/(p->dw->r->nent-1.0);
				ix = (unsigned int)floor(val);		/* Coordinate */
				if (ix > (ncal-2))
					ix = (ncal-2);
				w = val - (double)ix;		/* weight */
				for (j = 0; j < 3; j++) {
					val = p->cal[j][ix];
					p->dw->r->v[j][i] = val + w * (p->cal[j][ix+1] - val);
					/* Implement tvenc here rather than dispwin, so that the order is correct */
					if (out_tvenc) {
						p->dw->r->v[j][i] = ((235.0 - 16.0) * p->dw->r->v[j][i] + 16.0)/255.0;

						/* For video encoding the extra bits of precision are created by bit */
						/* shifting rather than scaling, so we need to scale the fp value to */
						/* account for this. */
						if (p->dw->edepth > 8)
							p->dw->r->v[j][i] =
							           (p->dw->r->v[j][i] * 255 * (1 << (p->dw->edepth - 8)))
							           /((1 << p->dw->edepth) - 1.0); 	
					}
				}
			}
			if (p->dw->set_ramdac(p->dw, p->dw->r, 0)) {
				a1logd(log,1,"new_disprd failed becayse set_ramdac failed\n");
				a1logv(p->log, 1, "Failed to set RAMDAC to desired calibration.\n");
				a1logv(p->log, 1, "Perhaps the operating system is being fussy ?\n");
				if (errc != NULL) *errc = 4;
				return NULL;
			}
		}
	}

	a1logd(log,1,"new_disprd succeeded\n");
	return p;
}