summaryrefslogtreecommitdiff
path: root/device-functions.c
blob: a0db6d928cb320f07c26e850a8ddc1bab8915d85 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
#include "device-functions.h"
#include "globals.h"
#include "version.h"
#include "error_utils.h"
#include "i2c.h"
#include "bus.h"
#include "lcd.h"
#include "flash.h"
#include "menus.h"
#include <math.h>
#include <glib.h>
#include <libuser/user.h>
#include <libuser/config.h>
#include <security/pam_appl.h>
#include <security/pam_misc.h>


static void start_gate_override ();
static void stop_gate_override ();
static void set_shiftreg_bits(int shiftreg, int start_at_bit, int numbits, int value);


#define ONE_BIT 1
#define TWO_BITS 2
#define THREE_BITS 3
#define FOUR_BITS 4
#define FIVE_BITS 5
#define SIX_BITS 6
#define SEVEN_BITS 7
#define EIGHT_BITS 8

#define SR_0 0
#define SR_1 1
#define SR_2 2
#define SR_3 3

#define POS_0 0
#define POS_1 1
#define POS_2 2
#define POS_3 3
#define POS_4 4
#define POS_5 5
#define POS_6 6
#define POS_7 7
#define POS_8 8
#define POS_9 9
#define POS_10 10
#define POS_11 11
#define POS_12 12
#define POS_13 13
#define POS_14 14
#define POS_15 15
#define POS_16 16
#define POS_17 17
#define POS_18 18
#define POS_19 19

#define XTR_POS 14

#define BIT_HIGH 1
#define BIT_LOW 0

void idn_string(gchar** response)
{
	*response = g_strdup_printf ("AVTECH ELECTROSYSTEMS,%s,SN:%s,v%s",
	                             globals.Flash.model_num,
	                             globals.Flash.serial_num,
	                             FW_VERSION);
}


void Main_Rst (void)
{
	int i;

	globals.Flags.extended_ampl_min_max=NO;

	// go backwards, so channel 0 overrides everything
	for (i=globals.Flash.channels-1; i>=0; --i) {

		globals.ChannelState[i].route_primary=1;
		globals.ChannelState[i].route_secondary=1;
		globals.ChannelState[i].frequency=globals.Flash.min_freq[i];
		globals.ChannelState[i].delay=globals.Flash.min_delay[i];

		if (globals.Flash.min_pw[i] > 0.0) {
			globals.ChannelState[i].pw=globals.Flash.min_pw[i];
		} else {
			globals.ChannelState[i].pw=0.0;
		}

		if (globals.Flash.ampl_min_max_only[i] || (globals.Flash.min_ampl[i] > 0.0)) {
			globals.ChannelState[i].amplitude = globals.Flash.min_ampl[i];
		} else {
			globals.ChannelState[i].amplitude=0.0;
		}
		globals.ChannelState[i].offset=0.0;

		globals.ChannelState[i].zout=globals.Flash.zout_min[i];
		globals.ChannelState[i].hold_setting = hold_width;
		globals.ChannelState[i].double_pulse = double_off;
		globals.ChannelState[i].pw_ctrl_mode = pw_normal;
		globals.ChannelState[i].func_mode = pulse_mode_on;
		globals.ChannelState[i].polarity = globals.Flash.invert_by_default[i];
		globals.ChannelState[i].output_state = output_off;
		globals.ChannelState[i].gate_type = gate_sync;
		globals.ChannelState[i].trigger_source = source_internal;
		globals.ChannelState[i].amp_mode = amp_mode_normal;
		globals.ChannelState[i].os_mode = os_mode_normal;
		globals.ChannelState[i].gate_level = gate_low;
		globals.ChannelState[i].load_type= globals.Flash.low_load_type[i];
		globals.ChannelState[i].test_delay_mode = NO;
		globals.ChannelState[i].logic_level = logic_ttl;
		globals.ChannelState[i].burst_count = 1 && !globals.Flash.burst_func[i];
		globals.ChannelState[i].burst_time = globals.Constraints.composite_min_burst_time[i];
		globals.ChannelState[i].rise_time = globals.Flash.min_rise_time[i];
		globals.ChannelState[i].soft_current_limit = globals.Flash.max_soft_current_limit[i];
		globals.ChannelState[i].vcc1 = 0.0;
		globals.ChannelState[i].vcc2 = globals.Flash.vcc2_min[i];
		globals.ChannelState[i].vlogic = 0.0;
		globals.ChannelState[i].slew = globals.Flash.min_slew[i];

		globals.Flags.do_check_settings=NO;   /* don't check for conflicting settings */
		Set_Pw(0,0,0,i,globals.ChannelState[i].pw,0);

		Set_Route(i,ROUTE_PRIMARY,globals.ChannelState[i].route_primary);
		Set_Route(i,ROUTE_SECONDARY,globals.ChannelState[i].route_secondary);

		Set_frequency(0,0,0,i,globals.ChannelState[i].frequency);
		Set_Delay(0,0,0,i,globals.ChannelState[i].delay);
		Set_Double(i,globals.ChannelState[i].double_pulse);
		Set_Pwmode(i,globals.ChannelState[i].pw_ctrl_mode);
		Set_Func(i,globals.ChannelState[i].func_mode);
		Set_Pol(i,globals.ChannelState[i].polarity);
		Set_Gate_Sync(i,globals.ChannelState[i].gate_type);
		Set_Gate_Level(i,globals.ChannelState[i].gate_level);
		Set_EA(i,globals.ChannelState[i].amp_mode);
		Set_EO(i,globals.ChannelState[i].os_mode);
		if (globals.Flash.switchable_zout[i]) {
			Set_zout(i,globals.ChannelState[i].zout,1);
		}

		Set_Load(i,globals.ChannelState[i].load_type);
		Set_Logic_Level(i,globals.ChannelState[i].logic_level);
		Set_rise_time(0,0,0,i,globals.ChannelState[i].rise_time);
		Set_slew(0,0,0,i,globals.ChannelState[i].slew);
		Set_current_limit(0,i,globals.ChannelState[i].soft_current_limit);

		if (globals.Flash.max_burst_count[i]>1) {
			Set_Burst_Count(i,globals.ChannelState[i].burst_count,globals.ChannelState[i].burst_time);
		}

		Set_Trig_Source(i,globals.ChannelState[i].trigger_source);

		Set_Amplitude(0,0,0,0,0,0,i,globals.ChannelState[i].amplitude,0);
		Set_Offset(0,0,0,0,i,globals.ChannelState[i].offset);
		Set_Output_State(i,globals.ChannelState[i].output_state);

		Set_current_limit(0,i,globals.ChannelState[i].soft_current_limit);

		Set_avrq_ampl(0,0,0,2,globals.ChannelState[i].vcc1);
		Set_avrq_ampl(0,0,0,3,globals.ChannelState[i].vcc2);
		Set_avrq_ampl(0,0,0,4,globals.ChannelState[i].vlogic);
		globals.Flags.do_check_settings=YES;  /* check for conflicting settings */
	}

	// establishes min/max values for queries, but reports no errors
	Error_check(globals.ChannelState);

	Ctrl_PRF_Limiter(1);

	globals.Timers.normal_relay_bounce_time_in_milliseconds=1.0e3 * globals.Flash.relay_delay_in_sec;
	globals.Timers.Relay_Switching_Delay_in_Milliseconds=globals.Timers.normal_relay_bounce_time_in_milliseconds;

	// reset all transient flags
	globals.Flags = globals.DefaultFlags;

	Menu_Clear_Buttons();
}


void set_dac(int dac, int word)
{
	/* allows dacs to be disabled (using dac=-1, for example) */
	if ((dac >= 0) && (dac < 8)) {
		globals.Registers.parallel_DAC_reg[dac]=word;
	}
}


int Set_Amplitude(int check_possible_only,int pol_override,int override_on,int word_override,int range_override,
                  int switch_range_only,int channel,float new_ampl,int called_from_set_pw)
{
	int word_out;	  /* what is sent to the DAC */
	int relay_range,atten_range,old_range,old_actual_pol;	  /* selects relay range */
	int UseNegData;	/* if polarity is negative and separate piece-wise linear data is available for neg */
	int point_found;
	int entry;
	int actual_pol;

	if (globals.Flash.enable_avrq_extra_ampls && channel) {
		return Set_avrq_ampl(check_possible_only,word_override,range_override,channel,new_ampl);
	}
	if (globals.Flash.enable_avrq_extra_ampls && !channel) {
		if ((new_ampl>=0.0) && (new_ampl<globals.Flash.ampl_zero_equiv[channel])) {
			new_ampl=globals.Flash.ampl_zero_equiv[channel];
		}
		if ((new_ampl<0.0) && (new_ampl>-globals.Flash.ampl_zero_equiv[channel])) {
			new_ampl=-globals.Flash.ampl_zero_equiv[channel];
		}
	}

	if (!globals.Flash.voltage_enabled[channel] && !globals.Flash.current_enabled[channel]) {
		return Unrecognized;
	}

	/* abandon if high channel selected by user but not enabled by firmware */
	if (channel && !globals.Flash.ChanKey_amplitude) {
		return InvalidChannel;
	}

	/* keep "-0" in negative area, to avoid using zeroed positive data */
	if (	new_ampl<=smallest_allowed_number
	                && new_ampl>=-smallest_allowed_number
	                && !(globals.Flash.max_ampl[channel]>0) 	) {
		new_ampl=-smallest_allowed_number;
	}

	/* Check for min abs value, step size */
	if (globals.Flash.ampl_min_abs_value[channel] > 0.0) {
		if ((new_ampl < 0.0) &&
		                (new_ampl > -globals.Flash.ampl_min_abs_value[channel])) {
			new_ampl = -globals.Flash.ampl_min_abs_value[channel];
		}
		if ((new_ampl >= 0.0) &&
		                (new_ampl < globals.Flash.ampl_min_abs_value[channel])) {
			new_ampl = globals.Flash.ampl_min_abs_value[channel];
		}
	}

	/* For units with large amplitude step sizes (AVRQ-2-B-PN-EVE) */
	if (globals.Flash.ampl_step_size[channel] > 0.0) {
		new_ampl = ((int) (new_ampl / globals.Flash.ampl_step_size[channel])) * globals.Flash.ampl_step_size[channel];
	}

	if (!check_possible_only) {
		int i, error_num;
		for (i=0; i<max_channels; ++i) {
			TestState[i]=globals.ChannelState[i];
		}
		TestState[channel].amplitude=new_ampl;
		if ((error_num=Error_check(TestState))) {
			return error_num;
		}

		/* determine the previous relay range */
		Set_VI_Control(pwl_ampl_values,channel,globals.ChannelState[channel].amplitude,&point_found,
		               &old_range,&atten_range,&UseNegData,&entry,&word_out,&old_actual_pol);
	}

	word_out = -1;
	relay_range = 0;


	/* find appropriate range/fine settings from piece-wise linear data in flash memory */

	if (override_on) {
		word_out=word_override;
		relay_range=range_override;
		actual_pol=pol_override;
	} else {
		/* set the amplitude controls now. */
		int status;
		if ((status=Set_VI_Control(pwl_ampl_values,channel,new_ampl,&point_found,
		                           &relay_range,&atten_range,&UseNegData,&entry,&word_out,&actual_pol))) {
			return status;
		}
	}

	if (check_possible_only) {
		if (point_found) {
			return OK;
		} else {
			return CalibrationMinMaxError;
		}
	}

	/* when switching to EA mode, need to switch range but keep DAC voltage zero */
	if (switch_range_only) {
		word_out=0;
	}


	/* if switching to a higher range with the same polarity, an extended delay may be needed to allow */
	/* capacitor banks to discharge (1011, 1015 series especially) */
	if ((relay_range>old_range) && (actual_pol==old_actual_pol) ) {
		globals.Timers.Relay_Switching_Delay_in_Milliseconds=(long) (1000L * globals.Flash.extended_relay_delay_in_sec);
	}


	set_dac(globals.Flash.ampl_DAC[channel],word_out);


	if (!channel) {
		if (!globals.Flash.ampl_ranges_for_ch2_only) {
			if ((globals.Flash.ChanKey_amplitude?globals.Flash.channels:1)<=1) {
				/* for regular, single-channel units use AMPL RANGE pins 0-4 */
				set_shiftreg_bits(SR_3, POS_7, FIVE_BITS, 1<<relay_range);
			} else {
				/* for CH1 of dual-channel units, use AMPL RANGE pin 0-2 for CH1, and 3-4 for CH2 */
				set_shiftreg_bits(SR_3, POS_7, THREE_BITS, 1<<relay_range);
			}
		}

		if (	(!actual_pol && globals.Flash.pol_relay_high_for_pos[channel])
		                ||	(actual_pol && !globals.Flash.pol_relay_high_for_pos[channel])	) {
			set_shiftreg_bits(SR_3, POS_13, ONE_BIT, BIT_HIGH);	/* set O.POL line high to switch pol relay to +, normally */
		} else {
			set_shiftreg_bits(SR_3, POS_13, ONE_BIT, BIT_LOW);	/* set O.POL line low to switch pol relay to -, normally */
		}

		// Are attenuators used?
		if (globals.Flash.attenuators[channel][0] > 0.0) {
			// deal with attenuator range - haven't done for CH2 yet

			// only implement one attenuator so far (range 0), out of possible max_attens (8!)
			// use I2C driver in future?
			if (atten_range == 0) {
				set_shiftreg_bits(SR_2, XTR_POS + 1, ONE_BIT, BIT_HIGH);
			} else {
				set_shiftreg_bits(SR_2, XTR_POS + 1, ONE_BIT, BIT_LOW);
			}
		}

	} else {

		if (!globals.Flash.ampl_ranges_for_ch2_only) {
			/* for CH2 of dual-channel units, use AMPL RANGE pin 2-3 */
			set_shiftreg_bits(SR_3, POS_10, TWO_BITS, 1<<relay_range);
		} else {
			/* sometimes CH2 can use pins 0-4 */
			set_shiftreg_bits(SR_3, POS_7, FIVE_BITS, 1<<relay_range);
		}

		int pol_bit = globals.Flash.polarity_xtra_rly[channel] + XTR_POS;
		if (new_ampl<0.0) {
			set_shiftreg_bits(SR_2, pol_bit, ONE_BIT, BIT_LOW);	/* set O.POL line low to switch pol relay to - */
		} else {
			set_shiftreg_bits(SR_2, pol_bit, ONE_BIT, BIT_HIGH);	/* set O.POL line high to switch pol relay to + */
		}
	}

	globals.Changes.update_amp=YES;

	globals.ChannelState[channel].amplitude=new_ampl;
	Set_Update_Chans();

	if ((relay_range!=old_range) && (globals.ChannelState[channel].output_state==output_on)) {
		globals.Flags.force_output_fully_off=YES;
	}

	/* update offset */
	if (globals.Flash.ampl_os_ranges_related[channel] && !globals.Changes.update_os) {
		Set_Offset(0,0,0,0,channel,globals.ChannelState[channel].offset);
	}

	/* ampl / pw tweaks */
	if (!called_from_set_pw) {
		Set_Pw(0,0,0,channel,globals.ChannelState[channel].pw,1);
	}

	/* ampl / delay tweaks */
	Set_Delay(0,0,0,channel,globals.ChannelState[channel].delay);
	Set_rise_time(0,0,0,channel,globals.ChannelState[channel].rise_time);

	return OK;
}


int Set_Pw(int check_possible_only,int word_override,int range_override,int channel,float set_pw,int called_from_set_ampl)
{
	int word_out;  /* what is sent to the DAC */
	int cap_range_control;
	int point_found,relay_range,dummy,UseNegData,entry;
	int status,actual_pol;

	/* abandon if high channel selected by user but not enabled by firmware */
	if (channel && !globals.Flash.ChanKey_pw) {
		return InvalidChannel;
	}

	/* for fixed PW units, set actual trigger PW to a reasonable minimum */
	if (globals.Flash.fixed_pw[channel]
	                && !check_possible_only
	                && !word_override
	                && !range_override
	                && (globals.Flash.fully_programmed==All_Programmed)) {
		set_pw=globals.Flash.min_pw[channel];
	}

	if (!check_possible_only) {
		int i, check_valid;
		for (i=0; i<max_channels; ++i) {
			TestState[i]=globals.ChannelState[i];
		}
		TestState[channel].pw=set_pw;
		if ((check_valid=Error_check(TestState))) {
			return check_valid;
		}
	}


	/* find appropriate range/fine settings from piece-wise linear data in flash memory */
	if (word_override) {
		word_out=word_override;
		relay_range=range_override;
	} else {
		/* set the pw controls now. */
		if ((status=Set_VI_Control(pwl_pw_values,channel,set_pw,&point_found,
		                           &relay_range,&dummy,&UseNegData,&entry,&word_out,&actual_pol))) {
			return status;
		}
	}


	if (check_possible_only) {
		if (point_found) {
			return OK;
		} else {
			return CalibrationMinMaxError;
		}
	}

	if (relay_range==0) {
		cap_range_control=0;
	} else {
		cap_range_control = 1 << (relay_range-1);
	}

	/* if this is for CH1, use the standard output chain */
	if (channel==0) {
		if (globals.Flash.special_pw_range_minimum[channel] > 0.0) {
			if (set_pw > globals.Flash.special_pw_range_minimum[channel]) {
				set_shiftreg_bits(SR_2, XTR_POS + 2, ONE_BIT, BIT_HIGH);
			} else {
				set_shiftreg_bits(SR_2, XTR_POS + 2, ONE_BIT, BIT_LOW);
			}
		}

		/* AVPP-style: lower PW range is voltage-controlled */
		if (globals.Flash.volt_ctrl_pw[channel]) {

			// reset PG B line (see below)
			set_shiftreg_bits(SR_2, XTR_POS + 5, ONE_BIT, BIT_LOW);

			/* use DAC8420 to control PW in lowest PW range */
			if (!relay_range) {
				set_dac(globals.Flash.pw_dac[channel],word_out);
				word_out=globals.Flash.fix_pw_dac_val[channel];
				/* Set to fixed value. */
				/* Isn't actually used to control PW in this mode, but may trigger following stages */

				/* Zout hardware/software is used in AVPP to control PW ranges, not Zout */
				Set_zout(channel,globals.Flash.zout_min[channel],0);
			} else {
				Set_zout(channel,globals.Flash.zout_max[channel],0);

				/* In AVPP units, the bottom range is voltage-controlled, and the upper range(s) are
					PWin=PWout. Therefore, shift the relay used by the upper ranges by one, to avoid
					changing capacitors. */

				if (relay_range==1) {
					cap_range_control=0;
					// set XTRA RLY 5 high in this range for AVR-E3-B-R5-N-M5, and other
					// units with PG A, B, and C. This corresponds to PG B.
					set_shiftreg_bits(SR_2, XTR_POS + 5, ONE_BIT, BIT_HIGH);
				} else {
					cap_range_control = 1 << (relay_range-2);
				}
			}
		}

		/* set fine controls */
		set_dac(4,word_out);

		/* set ranges */
		set_shiftreg_bits(SR_3, POS_0, SEVEN_BITS, cap_range_control);
	}

	if (channel==1) {
		/* if this is for CH2, use the standard 1021D dual-PW board, which has a PCF8574 for I/O, */
		/* unless it is a voltage-controlled scheme like the ISI units. */
		if (!globals.Flash.volt_ctrl_pw[channel]) {
			control_pcb107(Second_PW_Port,globals.Flash.pw_dac[channel],word_out,relay_range);
		} else {
			/* ISI-style units have voltage-controlled PW and two ranges */
			set_dac(globals.Flash.pw_dac[channel],word_out);

			/* two ranges controlled by XTRA-RLY2 line */
			set_shiftreg_bits(SR_2, XTR_POS + 2, ONE_BIT, relay_range);
		}
	}

	/* need a center-frequency control voltage for monocycle generators, to space the + and - parts of the monocycle. */
	/* use CH2 calibration to do this */
	if (globals.Flash.is_monocycle[0] && channel==0) {
		if ((status=Set_VI_Control(pwl_pw_values,1,set_pw,&point_found,
		                           &relay_range,&dummy,&UseNegData,&entry,&word_out,&actual_pol))) {
			return status;
		}
		set_dac(globals.Flash.monocycle_dac[0],word_out);
	}

	globals.ChannelState[channel].pw=set_pw;
	Set_Update_Chans();

	if (!called_from_set_ampl) {
		Set_Amplitude(0,0,0,0,0,0,channel,globals.ChannelState[channel].amplitude,1);
	}

	return OK;
}


int Set_Offset(int check_possible_only,int override_on,int word_override,int range_override,int channel,float new_offset)
{
	int word_out;	  /* what is sent to the DAC */
	int point_found;
	int entry,dummy0,dummy1,dummy2,dummy3;
	int actual_pol;
	int old_range,relay_range;

	if (!globals.Flash.voltage_offset_enabled[channel] && !globals.Flash.current_offset_enabled[channel]) {
		return Unrecognized;
	}

	/* abandon if high channel selected by user but not enabled by firmware */
	if (channel && !globals.Flash.ChanKey_offset) {
		return InvalidChannel;
	}

	word_out = -1;
	point_found = 0;

	if (!check_possible_only) {
		int i, error_num;
		for (i=0; i<max_channels; ++i) {
			TestState[i]=globals.ChannelState[i];
		}
		TestState[channel].offset=new_offset;
		if ((error_num=Error_check(TestState))) {
			return error_num;
		}

		/* determine the previous relay range */
		Set_VI_Control(pwl_os_values,channel,globals.ChannelState[channel].offset,&point_found,
		               &old_range,&dummy0,&dummy1,&dummy2,&word_out,&dummy3);
	}

	if (override_on) {
		relay_range=range_override;
		word_out=word_override;
	} else {
		int status;
		if ((status=Set_VI_Control(pwl_os_values,channel,new_offset,&point_found,
		                           &relay_range,&dummy0,&dummy2,&entry,&word_out,&actual_pol))) {
			return status;
		}
	}

	if (check_possible_only) {
		if (point_found) {
			return OK;
		} else {
			return CalibrationMinMaxError;
		}
	}

	set_dac(globals.Flash.os_DAC[channel],word_out);

	globals.Changes.update_os=YES;

	globals.ChannelState[channel].offset=new_offset;
	Set_Update_Chans();

	if ((relay_range!=old_range) && (globals.ChannelState[channel].output_state==output_on)) {
		globals.Flags.force_output_fully_off=YES;
	}

	if ((globals.Flash.ampl_coupled_to_os[channel] || globals.Flash.ampl_os_ranges_related[channel]) && !globals.Changes.update_amp) {
		Set_Amplitude(0,0,0,0,0,0,channel,globals.ChannelState[channel].amplitude,0);
	}

	/* change amplitude range if required for calibration */
	if (override_on) {
		Set_Amplitude(0,0,1,0,relay_range,0,channel,0.0,0);
	}

	/* increase PW if required to compensate for series output diode turn-on time */
	if (globals.Flash.distort_Y[channel] != 0.0) {
		Set_Pw(0,0,0,channel,globals.ChannelState[channel].pw,0);
	}

	return OK;
}


int Set_frequency(int check_possible_only,int word_override,int range_override,int channel,float set_freq)
{
	float new_pw;
	int point_found,relay_range,UseNegData,entry,actual_pol,old_range,dummy;
	int word_out;	/* what is sent to the DAC */

	/* abandon if high channel selected by user but not enabled by firmware */
	if (channel && !globals.Flash.ChanKey_frequency) {
		return InvalidChannel;
	}

	word_out = -1;

	/* check new duty cycle, if pw fixed */
	if (globals.ChannelState[channel].hold_setting==hold_width) {
		new_pw=globals.ChannelState[channel].pw;
	} else {
		new_pw=globals.ChannelState[channel].pw * globals.ChannelState[channel].frequency/set_freq;
	}

	if (!check_possible_only) {
		int i, check_valid;
		for (i=0; i<max_channels; ++i) {
			TestState[i]=globals.ChannelState[i];
		}
		TestState[channel].pw=new_pw;
		TestState[channel].frequency=set_freq;
		if ((check_valid=Error_check(TestState))) {
			return check_valid;
		}

		/* added Feb 23/05 */
		/* determine the previous relay range */
		Set_VI_Control(pwl_period_values,channel,1.0/globals.ChannelState[channel].frequency,&point_found,
		               &old_range,&dummy,&UseNegData,&entry,&word_out,&actual_pol);
	}

	/* find appropriate range/fine settings from piece-wise linear data in flash memory */
	if (word_override) {
		word_out=word_override;
		relay_range=range_override;
	} else {
		/* set the amplitude controls now. */
		int status;
		if ((status=Set_VI_Control(pwl_period_values,channel,1.0/set_freq,&point_found,
		                           &relay_range,&dummy,&UseNegData,&entry,&word_out,&actual_pol))) {
			return status;
		}
	}

	if (check_possible_only) {
		if (point_found) {
			return OK;
		} else {
			return CalibrationMinMaxError;
		}
	}

	if (globals.Flash.is_func_gen[channel]) {
		set_dac(globals.Flash.freq_dac[channel],word_out);

		/* Function generator PRF range controlled by XTRA-RLY 1-3 lines. */
		/* Range=0 disables oscillator, for amplifier mode. */

		if (globals.ChannelState[channel].func_mode==amp_mode_on) {
			relay_range=0;
		}

		set_shiftreg_bits(SR_2, XTR_POS + 1, THREE_BITS, relay_range);

		if ((relay_range!=old_range) && (globals.ChannelState[channel].output_state==output_on)) {
			globals.Flags.force_output_fully_off=YES;
		}
	}

	else {
		int cap_range_control = 0;

		if (relay_range) {
			cap_range_control = 1 << (relay_range-1);
		}

		set_dac(globals.Flash.freq_dac[channel],word_out);
		set_shiftreg_bits(SR_2, POS_0, SEVEN_BITS, cap_range_control);
	}

	g_print_debug("freq range %d, word %d\n",relay_range,word_out);

	globals.ChannelState[channel].frequency=set_freq;

	Set_Pw(0,0,0,channel,new_pw,0);
	Set_Update_Chans();

	return OK;
}


int Set_Delay(int check_possible_only,int word_override,int range_override,int channel,float set_delay)
{
	int word_out;  /* what is sent to the DAC */
	int cap_range_control;	/* what is actually sent to shift register */
	float setting;
	int point_found,relay_range,UseNegData,entry,actual_pol,dummy;

	/* abandon if high channel selected by user but not enabled by firmware */
	if (channel && !globals.Flash.ChanKey_delay) {
		return InvalidChannel;
	}

	if (!check_possible_only) {
		int i, check_valid;
		for (i=0; i<max_channels; ++i) {
			TestState[i]=globals.ChannelState[i];
		}
		TestState[channel].delay=set_delay;
		if ((check_valid=Error_check(TestState))) {
			return check_valid;
		}
	}

	setting=set_delay-globals.Flash.propagation_delay[channel];

	/* tweak depending on polarity */
	if (globals.ChannelState[channel].amplitude<0.0) {
		setting -= globals.Flash.delay_pol_tweak[channel][1];
	} else {
		setting -= globals.Flash.delay_pol_tweak[channel][0];
	}

	if (setting >= 0.0) {
		Set_AdvDel(channel,to_Advance);
	} else {
		Set_AdvDel(channel,to_Delay);
		setting *= -1;
	}

	setting=setting+globals.Flash.delay_shrink[channel];

	/* protect against impossible settings during first turn-on */
	if (setting<zero_equiv_timing) {
		return HardwareError;
	}

	/* find appropriate range/fine settings from piece-wise linear data in flash memory */
	if (word_override) {
		word_out=word_override;
		relay_range=range_override;
	} else {
		/* set the amplitude controls now. */
		int status;
		if ((status=Set_VI_Control(pwl_delay_values,channel,setting,&point_found,
		                           &relay_range,&dummy,&UseNegData,&entry,&word_out,&actual_pol))) {
			return status;
		}
	}

	if (check_possible_only) {
		if (point_found) {
			return OK;
		} else {
			return CalibrationMinMaxError;
		}
	}


	if (relay_range==0) {
		cap_range_control=0;
	} else {
		cap_range_control = 1 << (relay_range-1);
	}

	if (channel==0) {
		set_dac(globals.Flash.delay_dac[channel],word_out);
		set_shiftreg_bits(SR_2, POS_8, SEVEN_BITS, cap_range_control);
	}

	if (channel==1) {
		control_pcb107(Second_Dly_Port,globals.Flash.delay_dac[channel],word_out,relay_range);
	}

	globals.ChannelState[channel].delay=set_delay;
	Set_Update_Chans();

	return OK;
}


int Set_Double(int channel,int new_setting)
{
	int error_num;
	int i;

	/* abandon if high channel selected by user but not enabled by firmware */
	if (channel && !globals.Flash.ChanKey_double_pulse) {
		return InvalidChannel;
	}

	for (i=0; i<max_channels; ++i) {
		TestState[i]=globals.ChannelState[i];
	}
	TestState[channel].double_pulse=new_setting;
	if ((error_num=Error_check(TestState))) {
		return error_num;
	}

	if (new_setting == double_off) {
		set_shiftreg_bits(SR_0, POS_5, ONE_BIT, BIT_LOW);	// turn double-pulse off
		Ctrl_PRF_Limiter (1);				// normal prf limiting
	} else {
		set_shiftreg_bits(SR_0, POS_5, ONE_BIT, BIT_HIGH);	// turn double-pulse on
		Ctrl_PRF_Limiter (0);					// disable prf limiter
	}

	globals.ChannelState[channel].double_pulse=new_setting;
	Set_Update_Chans();

	return OK;
}


void Ctrl_PRF_Limiter(int enable)
{
	if (enable && globals.Flash.prf_limiter) {
		set_shiftreg_bits(SR_0, POS_7, ONE_BIT, BIT_HIGH);	/* turn prf limiter on */
	} else {
		set_shiftreg_bits(SR_0, POS_7, ONE_BIT, BIT_LOW);		/* turn prf limiter off */
	}

	Main_update_shift_registers();

	return;
}


void Set_Mux(int channel)
{
	int mux_out;

	if (globals.ChannelState[channel].func_mode==dc_mode_on && globals.ChannelState[channel].polarity==pol_norm) {
		mux_out=4;
	} else if (globals.ChannelState[channel].func_mode==dc_mode_on && globals.ChannelState[channel].polarity!=pol_norm) {
		mux_out=5;
	} else if (globals.ChannelState[channel].pw_ctrl_mode!=pw_in_out && globals.ChannelState[channel].polarity==pol_norm) {
		mux_out=2;
	} else if (globals.ChannelState[channel].pw_ctrl_mode!=pw_in_out && globals.ChannelState[channel].polarity!=pol_norm) {
		mux_out=3;
	} else if (globals.ChannelState[channel].polarity==pol_norm) {
		mux_out=0;
	} else if (globals.ChannelState[channel].polarity!=pol_norm) {
		mux_out=1;
	}

	if (globals.ChannelState[channel].test_delay_mode==YES) {
		mux_out=6;
	}

	set_shiftreg_bits(SR_1, POS_0, THREE_BITS, mux_out);
}


int Set_Func(int channel,int mode)
{
	int i;
	int check_valid;

	/* abandon if high channel selected by user but not enabled by firmware */
	if (channel && !globals.Flash.ChanKey_func_mode) {
		return InvalidChannel;
	}

	if ( (mode==dc_mode_on) && !globals.Flash.dc_mode_allowed[channel]) {
		return SyntaxError;
	}

	/* some modes are for function generators only */
	if ( ((mode==sin_mode_on) || (mode==squ_mode_on) || (mode==tri_mode_on) || (mode==amp_mode_on))
	                && !globals.Flash.is_func_gen[channel]) {
		return SyntaxError;
	}

	for (i=0; i<max_channels; ++i) {
		TestState[i]=globals.ChannelState[i];
	}
	TestState[channel].func_mode=mode;
	if ((check_valid=Error_check(TestState))) {
		return check_valid;
	}

	if (globals.Flash.is_func_gen[channel]) {
		/* set sin, tri, squ lines */
		set_shiftreg_bits(SR_3, POS_17, THREE_BITS, mode);

		/* set amplify mode line */

		int amplify_bit = XTR_POS + globals.Flash.ext_amplify_xtra_rly[channel];
		if (mode==amp_mode_on) {
			set_shiftreg_bits(SR_2, amplify_bit, ONE_BIT, BIT_HIGH);
		} else {
			set_shiftreg_bits(SR_2, amplify_bit, ONE_BIT, BIT_LOW);
		}
	}


	/* reset pulse width and delay to safe values */
	if (globals.ChannelState[channel].func_mode!=mode) {
		globals.ChannelState[channel].func_mode=mode;

		Set_Pw(0,0,0,channel,globals.Flash.min_pw[channel],0);
		Set_Delay(0,0,0,channel,globals.Flash.min_delay[channel]);

		/* update frequency, to reset func gen control lines */
		Set_frequency(0,0,0,channel,globals.ChannelState[channel].frequency);

		Set_current_limit(0,channel,globals.ChannelState[channel].soft_current_limit);
	}

	Set_Mux(channel);
	Set_Update_Chans();

	return OK;
}


int Set_Pol(int channel,int mode)
{
	int error_num, i;

	/* abandon if high channel selected by user but not enabled by firmware */
	if (channel && !globals.Flash.ChanKey_polarity) {
		return InvalidChannel;
	}

	/* duty cycle check */
	for (i=0; i<max_channels; ++i) {
		TestState[i]=globals.ChannelState[i];
	}
	TestState[channel].polarity=mode;
	if ((error_num=Error_check(TestState))) {
		return error_num;
	}

	globals.ChannelState[channel].polarity=mode;

	Set_Mux(channel);
	Set_Update_Chans();

	return OK;
}


int Set_Hold(int channel,int mode)
{
	/* abandon if high channel selected by user but not enabled by firmware */
	if (channel && !globals.Flash.ChanKey_hold_setting) {
		return InvalidChannel;
	}

	globals.ChannelState[channel].hold_setting=mode;
	Set_Update_Chans();

	return OK;
}


int Set_Output_State(int channel,int mode)
{
	int i, error_num;

	/* abandon if high channel selected by user but not enabled by firmware */
	if (channel && !globals.Flash.ChanKey_output_state) {
		return InvalidChannel;
	}

	for (i=0; i<max_channels; ++i) {
		TestState[i]=globals.ChannelState[i];
	}
	TestState[channel].output_state=mode;
	if ((error_num=Error_check(TestState))) {
		return error_num;
	}

	/* suppress triggering during relay bounce */
	/* set gate bit high, if not already high */

	for (i=0; i<(globals.Flash.ChanKey_frequency?globals.Flash.channels:1); ++i)
		if (globals.ChannelState[i].trigger_source!=source_hold) {
			bus_setpin(O_GATE, 1);
		}

	if (mode==output_on || !globals.Flash.on_off_used) {
		/* do not permit enabling of output during overload condition */
		if ( (I2C_Read(PCF8574A+Button_Press_Port) & 0x40) == 0) {
			return Overload_Detected;
		}

		bus_setpin(OUTPUT_RELAY, 1);	 /* turn output on */
		bus_setpin(PW_ENABLE, 1);	  /* enable PW circuit */

		g_usleep (800e3);		/* wait for extended-off circuit to work */

		globals.Timers.last_activity_at[channel] = sec_timer();
	} else {
		bus_setpin(PW_ENABLE, 0);	 /* disable PW circuit */
		bus_setpin(OUTPUT_RELAY, 0);	 /* turn output off */
		globals.Timers.last_activity_at[channel] = 0L;
	}

	globals.ChannelState[channel].output_state=mode;
	Set_Update_Chans();


	/* keep trigger suppressed during output relay update */
	/* trigger gate will be released at end of following Main_update_shift_registers(); */

	return OK;
}


int Set_Trig_Source(int channel,int mode)
{
	int gate_mode;
	int use_pw_ctrl_mode;
	int reset_freq;
	float use_freq;

	/* abandon if high channel selected by user but not enabled by firmware */
	if (channel && !globals.Flash.ChanKey_trigger_source) {
		return InvalidChannel;
	}

	use_pw_ctrl_mode = globals.ChannelState[channel].pw_ctrl_mode;
	use_freq = globals.ChannelState[channel].frequency;
	reset_freq = 0;

	if (globals.ChannelState[channel].trigger_source!=mode) {
		int i, error_num;
		for (i=0; i<max_channels; ++i) {
			TestState[i]=globals.ChannelState[i];
		}
		TestState[channel].trigger_source = mode;

		if ((globals.ChannelState[channel].trigger_source != source_hold) && (mode != source_hold)) {
			reset_freq = 1;
			use_freq = globals.Flash.min_freq[channel];
			// turn ab mode off when switching trigger source
			if (use_pw_ctrl_mode == pw_in_out) {
				use_pw_ctrl_mode = pw_normal;
			}
		}

		TestState[channel].pw_ctrl_mode = use_pw_ctrl_mode;
		TestState[channel].frequency = use_freq;

		if ((error_num=Error_check(TestState))) {
			return error_num;
		}

		if (reset_freq) {
			Set_frequency(0,0,0,channel,use_freq);
			Set_Pwmode(channel,use_pw_ctrl_mode);
		}
	}

	globals.ChannelState[channel].trigger_source=mode;
	Set_Update_Chans();


	/* Function generator operate in the "external" mode only. The internal oscillator is never used. */
	if (globals.Flash.is_func_gen[channel]) {
		mode=source_external;
	}

	gate_mode = 0;
	if (mode==source_internal) {
		/* frequency is automatically lowered if pw or delay have been changed to conflicting */
		/* settings while in a non-internal mode */
		set_shiftreg_bits(SR_0, POS_2, THREE_BITS, 0x0);
	} else if (mode==source_external) {
		globals.ChannelState[channel].hold_setting=hold_width;
		set_shiftreg_bits(SR_0, POS_2, THREE_BITS, 0x3);
	} else if (mode==source_manual) {
		globals.ChannelState[channel].hold_setting=hold_width;
		set_shiftreg_bits(SR_0, POS_2, THREE_BITS, 0x1);
	} else if (mode==source_hold) {
		gate_mode=1;
	} else if (mode==source_immediate) {
		set_shiftreg_bits(SR_0, POS_2, THREE_BITS, 0x4);
		Main_update_shift_registers();
		set_shiftreg_bits(SR_0, POS_2, THREE_BITS, 0x7);
	}

	Main_update_shift_registers();
	bus_setpin(O_GATE, gate_mode);	/* change gate only after new source set */

	return OK;
}


int Set_Gate_Sync(int channel,int mode)
{
	/* abandon if high channel selected by user but not enabled by firmware */
	if (channel && !globals.Flash.ChanKey_gate_type) {
		return InvalidChannel;
	}

	if (mode==gate_sync) {
		set_shiftreg_bits(SR_0, POS_0, ONE_BIT, BIT_LOW);
	} else {
		set_shiftreg_bits(SR_0, POS_0, ONE_BIT, BIT_HIGH);
	}

	globals.ChannelState[channel].gate_type=mode;
	Set_Update_Chans();

	return OK;
}


int Set_Gate_Level(int channel,int mode)
{
	/* abandon if high channel selected by user but not enabled by firmware */
	if (channel && !globals.Flash.ChanKey_gate_level) {
		return InvalidChannel;
	}

	if (mode==0) {
		set_shiftreg_bits(SR_0, POS_1, ONE_BIT, BIT_HIGH);
	} else {
		set_shiftreg_bits(SR_0, POS_1, ONE_BIT, BIT_LOW);
	}

	globals.ChannelState[channel].gate_level=mode;
	Set_Update_Chans();

	return OK;
}


static void start_gate_override ()
{
	/* just set gate bit high, if not already high */
	int i;
	for (i=0; i<(globals.Flash.ChanKey_frequency?globals.Flash.channels:1); ++i)
		if (globals.ChannelState[i].trigger_source!=source_hold) {
			bus_setpin(O_GATE, 1);
		}
}


static void stop_gate_override ()
{
	/* release gate (if not in hold mode) */
	int i;
	for (i=0; i<(globals.Flash.ChanKey_frequency?globals.Flash.channels:1); ++i)
		if (globals.ChannelState[i].trigger_source!=source_hold) {
			bus_setpin(O_GATE, 0);
		}
}


int Set_zout(int channel,int setting,int really_for_zout)
{
	int update_zout_slowly;

	/* abandon if high channel selected by user but not enabled by firmware */
	if (channel && !globals.Flash.ChanKey_zout) {
		return InvalidChannel;
	}

	update_zout_slowly=NO;

	/* The Zout hardware and software is controlled by PW commands in the AVPP. */
	/* This mode is signalled by really_for_zout=0 */

	/* first channel uses dedicated Zout line */
	if (channel==0) {
		if (setting!=globals.Flash.zout_max[channel]) {
			set_shiftreg_bits(SR_3, POS_12, ONE_BIT, BIT_HIGH);	/* power zout relay */
		} else {
			set_shiftreg_bits(SR_3, POS_12, ONE_BIT, BIT_LOW);	/* de-power zout relay */
		}
	}

	/* second channel uses dedicated xtra-rly2 line */
	if (channel==1) {
		if (setting!=globals.Flash.zout_max[channel]) {
			set_shiftreg_bits(SR_2, XTR_POS + 2, ONE_BIT, BIT_HIGH);	/* power zout relay */
		} else {
			set_shiftreg_bits(SR_2, XTR_POS + 2, ONE_BIT, BIT_LOW);	/* de-power zout relay */
		}
	}

	if (setting!=globals.ChannelState[channel].zout) {
		globals.Changes.update_zout=YES;

		/* allow extra time for cap banks to discharge if going from
			50 Ohms to 2 Ohm Zout */
		if (setting<globals.ChannelState[channel].zout) {
			update_zout_slowly=YES;
		}
	}

	globals.ChannelState[channel].zout=setting;
	Set_Update_Chans();

	/* Skip this stuff if this is actually for AVPP PW control */
	if (really_for_zout) {
		if (globals.Changes.update_zout) {
			/* change of Zout may require change in amplitude controls */
			Set_Amplitude(0,0,0,0,0,0,channel,globals.ChannelState[channel].amplitude,0);
		}

		if (update_zout_slowly) {
			globals.Timers.Relay_Switching_Delay_in_Milliseconds=(long) (1000L * globals.Flash.extended_relay_delay_in_sec);
		}
	}

	return OK;
}


int Set_Load(int channel, float value)
{
	int error_num;

	/* abandon if high channel selected by user but not enabled by firmware */
	if (channel && !globals.Flash.ChanKey_load_type) {
		return InvalidChannel;
	}

	if (globals.Flash.enable_avrq_extra_ampls) {
		return Set_avrq_res(0,0,0,channel,value);
	}

	/* duty cycle check */
	int i;
	for (i=0; i<max_channels; ++i) {
		TestState[i]=globals.ChannelState[i];
	}
	TestState[channel].load_type=value;
	if ((error_num=Error_check(TestState))) {
		return error_num;
	}

	if (globals.ChannelState[channel].load_type!=value) {
		globals.Changes.update_load=YES;
	}

	globals.ChannelState[channel].load_type=value;
	Set_Update_Chans();

	if (globals.Changes.update_load) {
		/* change of load may require change in amplitude controls */
		Set_Amplitude(0,0,0,0,0,0,channel,globals.ChannelState[channel].amplitude,0);
	}

	return OK;
}


int Set_EA(int channel,int mode)
{
	char set_DAC_to_zero;

	/* abandon if high channel selected by user but not enabled by firmware */
	if (channel && !globals.Flash.ChanKey_amplitude) {
		return InvalidChannel;
	}

	if (!(globals.Flash.ea_enabled[channel]) && (mode==amp_mode_ea) ) {
		return SyntaxError;
	}
	if (!(globals.Flash.ext_amplify_enabled[channel]) && (mode==amp_mode_amplify) ) {
		return SyntaxError;
	}

	set_DAC_to_zero=YES;
	if (mode==amp_mode_amplify) {
		set_DAC_to_zero=NO;
	}

	/* set to max amplitude range when switching from normal to EA or Ext Amplify */
	if ( (globals.ChannelState[channel].amp_mode==amp_mode_normal) && (mode!=amp_mode_normal) ) {
		if (globals.ChannelState[channel].amplitude<0.0)
			Set_Amplitude(0,0,0,0,0,set_DAC_to_zero,channel,
			              globals.ChannelState[channel].amplitude=globals.Flash.min_ampl[channel],0); /* most negative */
		else
			Set_Amplitude(0,0,0,0,0,set_DAC_to_zero,channel,
			              globals.ChannelState[channel].amplitude=globals.Flash.max_ampl[channel],0); /* most positive */
	}


	/* protect when switching from EA or Ext Amplify back to normal */
	if ( (globals.ChannelState[channel].amp_mode!=amp_mode_normal) && (mode==amp_mode_normal) ) {
		if (globals.ChannelState[channel].amplitude<0.0) {
			Set_Amplitude(0,0,0,0,0,0,channel,globals.ChannelState[channel].amplitude=-smallest_allowed_number,0);
		} else {
			Set_Amplitude(0,0,0,0,0,0,channel,globals.ChannelState[channel].amplitude=smallest_allowed_number,0);
		}
	}


	if (globals.Flash.ea_enabled[channel]) {
		int ea_reg, ea_bit;

		if (!channel) {
			ea_bit = 16;
			ea_reg = SR_3;
		} else {
			ea_bit = globals.Flash.ea_xtra_rly[channel] + XTR_POS;
			ea_reg = SR_2;
		}

		if (mode==amp_mode_ea) {
			set_shiftreg_bits(ea_reg, ea_bit, ONE_BIT, BIT_HIGH);
		} else {
			set_shiftreg_bits(ea_reg, ea_bit, ONE_BIT, BIT_LOW);
		}
	}


	if (globals.Flash.ext_amplify_enabled[channel]) {
		int amplify_bit = XTR_POS + globals.Flash.ext_amplify_xtra_rly[channel];

		if (mode==amp_mode_amplify) {
			set_shiftreg_bits(SR_2, amplify_bit, ONE_BIT, BIT_HIGH);
		} else {
			set_shiftreg_bits(SR_2, amplify_bit, ONE_BIT, BIT_LOW);
		}
	}


	if (globals.ChannelState[channel].amp_mode!=mode) {
		globals.Changes.update_amp=YES;
	}

	globals.ChannelState[channel].amp_mode=mode;
	Set_Update_Chans();

	return OK;
}


int Set_AdvDel(int channel,int setting)
{
	if (setting==to_Advance) {
		set_shiftreg_bits(SR_0, POS_6, ONE_BIT, BIT_HIGH);	/* turn advance on */
	} else {
		set_shiftreg_bits(SR_0, POS_6, ONE_BIT, BIT_LOW);		/* turn delay on */
	}

	Set_Update_Chans();

	return OK;
}


int Set_Pwmode(int channel,int mode)
{
	/* abandon if high channel selected by user but not enabled by firmware */
	if (channel && !globals.Flash.ChanKey_pw) {
		return InvalidChannel;
	}

	if (!(globals.Flash.pw_ab_mode_enabled[channel]) && (mode==pw_in_out)) {
		return SyntaxError;
	}

        if (!(globals.Flash.ew_enabled[channel]) && (mode==pw_ew_ext)) {
                return SyntaxError;
        }

	if ((mode==pw_in_out) && (globals.ChannelState[channel].trigger_source!=source_external)) {
		return AB_Mode_Error;
	}

	globals.ChannelState[channel].pw_ctrl_mode=mode;

	if (globals.Flash.ew_enabled[channel]) {
		if (mode==pw_ew_ext) {
			set_shiftreg_bits(SR_2, globals.Flash.ew_xtra_rly[channel] + XTR_POS, ONE_BIT, BIT_HIGH);
		} else {
			set_shiftreg_bits(SR_2, globals.Flash.ew_xtra_rly[channel] + XTR_POS, ONE_BIT, BIT_LOW);
		}
	}

	Set_Mux(0);
	Set_Update_Chans();

	return OK;
}


int Set_Update_Chans(void)
{
	int num_of_chan;

	num_of_chan=globals.Flash.channels;
	if (num_of_chan==0) {
		num_of_chan=1;
	}

	if (num_of_chan>1) {
		int i;
		if (!globals.Flash.ChanKey_frequency) for (i=1; i<num_of_chan; ++i) {
				globals.ChannelState[i].frequency=globals.ChannelState[0].frequency;
			}
		if (!globals.Flash.ChanKey_delay) for (i=1; i<num_of_chan; ++i) {
				globals.ChannelState[i].delay=globals.ChannelState[0].delay;
			}
		if (!globals.Flash.ChanKey_pw) for (i=1; i<num_of_chan; ++i) {
				globals.ChannelState[i].pw=globals.ChannelState[0].pw;
			}
		if (!globals.Flash.ChanKey_amplitude) for (i=1; i<num_of_chan; ++i) {
				globals.ChannelState[i].amplitude=globals.ChannelState[0].amplitude;
			}
		if (!globals.Flash.ChanKey_offset) for (i=1; i<num_of_chan; ++i) {
				globals.ChannelState[i].offset=globals.ChannelState[0].offset;
			}

		if (!globals.Flash.ChanKey_Curr_Mon_value) for (i=1; i<num_of_chan; ++i) {
				globals.ChannelState[i].Curr_Mon_value=globals.ChannelState[0].Curr_Mon_value;
			}
		if (!globals.Flash.ChanKey_Curr_Mon_offset) for (i=1; i<num_of_chan; ++i) {
				globals.ChannelState[i].Curr_Mon_offset=globals.ChannelState[0].Curr_Mon_offset;
			}

		if (!globals.Flash.ChanKey_zout) for (i=1; i<num_of_chan; ++i) {
				globals.ChannelState[i].zout=globals.ChannelState[0].zout;
			}
		if (!globals.Flash.ChanKey_hold_setting) for (i=1; i<num_of_chan; ++i) {
				globals.ChannelState[i].hold_setting=globals.ChannelState[0].hold_setting;
			}
		if (!globals.Flash.ChanKey_double_pulse) for (i=1; i<num_of_chan; ++i) {
				globals.ChannelState[i].double_pulse=globals.ChannelState[0].double_pulse;
			}
		if (!globals.Flash.ChanKey_pw) for (i=1; i<num_of_chan; ++i) {
				globals.ChannelState[i].pw_ctrl_mode=globals.ChannelState[0].pw_ctrl_mode;
			}
		if (!globals.Flash.ChanKey_func_mode) for (i=1; i<num_of_chan; ++i) {
				globals.ChannelState[i].func_mode=globals.ChannelState[0].func_mode;
			}
		if (!globals.Flash.ChanKey_polarity) for (i=1; i<num_of_chan; ++i) {
				globals.ChannelState[i].polarity=globals.ChannelState[0].polarity;
			}
		if (!globals.Flash.ChanKey_output_state) for (i=1; i<num_of_chan; ++i) {
				globals.ChannelState[i].output_state=globals.ChannelState[0].output_state;
			}
		if (!globals.Flash.ChanKey_gate_type) for (i=1; i<num_of_chan; ++i) {
				globals.ChannelState[i].gate_type=globals.ChannelState[0].gate_type;
			}
		if (!globals.Flash.ChanKey_trigger_source) for (i=1; i<num_of_chan; ++i) {
				globals.ChannelState[i].trigger_source=globals.ChannelState[0].trigger_source;
			}
		if (!globals.Flash.ChanKey_amp_mode) for (i=1; i<num_of_chan; ++i) {
				globals.ChannelState[i].amp_mode=globals.ChannelState[0].amp_mode;
			}
		if (!globals.Flash.ChanKey_gate_level) for (i=1; i<num_of_chan; ++i) {
				globals.ChannelState[i].gate_level=globals.ChannelState[0].gate_level;
			}
		if (!globals.Flash.ChanKey_load_type) for (i=1; i<num_of_chan; ++i) {
				globals.ChannelState[i].load_type=globals.ChannelState[0].load_type;
			}
		if (!globals.Flash.ChanKey_test_delay_mode) for (i=1; i<num_of_chan; ++i) {
				globals.ChannelState[i].test_delay_mode=globals.ChannelState[0].test_delay_mode;
			}
		if (!globals.Flash.ChanKey_os_mode) for (i=1; i<num_of_chan; ++i) {
				globals.ChannelState[i].os_mode=globals.ChannelState[0].os_mode;
			}
		if (!globals.Flash.ChanKey_Burst_Count) for (i=1; i<num_of_chan; ++i) {
				globals.ChannelState[i].burst_count=globals.ChannelState[0].burst_count;
			}
		if (!globals.Flash.ChanKey_Burst_Time) for (i=1; i<num_of_chan; ++i) {
				globals.ChannelState[i].burst_time=globals.ChannelState[0].burst_time;
			}
		if (!globals.Flash.ChanKey_rise_time) for (i=1; i<num_of_chan; ++i) {
				globals.ChannelState[i].rise_time=globals.ChannelState[0].rise_time;
			}
		if (!globals.Flash.ChanKey_slew) for (i=1; i<num_of_chan; ++i) {
				globals.ChannelState[i].slew=globals.ChannelState[0].slew;
			}

		for (i=1; i<num_of_chan; ++i) {
			globals.ChannelState[i].vcc1=globals.ChannelState[0].vcc1;
			globals.ChannelState[i].vcc2=globals.ChannelState[0].vcc2;
			globals.ChannelState[i].vlogic=globals.ChannelState[0].vlogic;
		}

	}

	return OK;
}


int Set_Amp_Calib(int channel,float meas_ampl)
{
	float change_ratio;
	int i,status;
	int point_found,relay_range,UseNegData,entry,word_out,actual_pol,atten_range;
	int eprom_loc;

	/* use for all channels */

	/* get current range and polarity settings */
	Set_VI_Control(pwl_ampl_values,channel,globals.ChannelState[channel].amplitude,&point_found,
	               &relay_range,&atten_range,&UseNegData,&entry,&word_out,&actual_pol);

	if (fabs(globals.ChannelState[channel].amplitude)<globals.Flash.ampl_zero_equiv[channel]) {
		return NeedNonZeroAmpl;
	}

	change_ratio = meas_ampl/globals.ChannelState[channel].amplitude;

	if (change_ratio>1.3 || change_ratio < 0.7) {
		return CalibrationPercentError;
	}

	for (i=0; i<10; ++i)
		globals.Flash.ampl_pwl_amp[channel][relay_range][UseNegData][i]=
		        globals.Flash.ampl_pwl_amp[channel][relay_range][UseNegData][i]*change_ratio;


	/* see if new data prevents min/max from being obtained */
	status=Check_MinMax_Cal(channel,pwl_ampl_values);

	if (status) {
		/* revert to original calibration */
		for (i=0; i<10; ++i)
			globals.Flash.ampl_pwl_amp[channel][relay_range][UseNegData][i]=
			        globals.Flash.ampl_pwl_amp[channel][relay_range][UseNegData][i]/change_ratio;
	}

	eprom_loc = (char *) &(globals.Flash.ampl_pwl_amp) - (char *) &(globals.Flash.flash_start);
	writeUserBlock(&globals.Flash, eprom_loc, sizeof(globals.Flash.ampl_pwl_amp));

	return status;
}


int Set_Mon_Calib(int channel,float meas_ampl)
{
	float change_ratio;
	int point_found,relay_range,UseNegData,entry,word_out,actual_pol,eprom_loc,atten_range;

	/* use for all channels */

	/* get current range and polarity settings */
	Set_VI_Control(pwl_ampl_values,channel,globals.ChannelState[channel].amplitude,&point_found,
	               &relay_range,&atten_range,&UseNegData,&entry,&word_out,&actual_pol);

	if (fabs(globals.ChannelState[channel].Curr_Mon_value)< (5.0 * globals.Flash.monitor_step[channel])) {
		return NeedNonZeroAmpl;
	}

	if (globals.Flash.sep_posneg_mon_ratio[channel] && globals.ChannelState[channel].amplitude<0.0) {
		UseNegData=1;
	} else {
		UseNegData=0;
	}

	change_ratio = meas_ampl/globals.ChannelState[channel].Curr_Mon_value;

	if (change_ratio>1.3 || change_ratio < 0.7) {
		return CalibrationPercentError;
	}

	globals.Flash.mon_vi_ratio[channel][relay_range][UseNegData]=globals.Flash.mon_vi_ratio[channel][relay_range][UseNegData]/change_ratio;

	eprom_loc = (char *) &(globals.Flash.mon_vi_ratio) - (char *) &(globals.Flash.flash_start);
	writeUserBlock(&globals.Flash, eprom_loc, sizeof(globals.Flash.mon_vi_ratio));

	return OK;
}


int Set_Logic_Level(int channel,int mode)
{
	if (channel==0) {
		if (mode==logic_ecl) {
			set_shiftreg_bits(SR_3, POS_14, ONE_BIT, BIT_HIGH);
		} else {
			set_shiftreg_bits(SR_3, POS_14, ONE_BIT, BIT_LOW);
		}
	}

	/* second channel uses xtra-rly3 */
	if (channel==1) {
		if (mode==logic_ecl) {
			set_shiftreg_bits(SR_3, XTR_POS + 3, ONE_BIT, BIT_HIGH);
		} else {
			set_shiftreg_bits(SR_3, XTR_POS + 3, ONE_BIT, BIT_LOW);
		}
	}

	globals.ChannelState[channel].logic_level=mode;
	Set_Update_Chans();

	return OK;
}


int Set_OS_Calib(int channel,float meas_ampl)
{
	float change_ratio;
	int i,status,eprom_loc;

	if (fabs(globals.ChannelState[channel].offset)<globals.Flash.ampl_zero_equiv[channel]) {
		return NeedNonZeroAmpl;
	}

	change_ratio = meas_ampl/globals.ChannelState[channel].offset;

	if (change_ratio>1.3 || change_ratio < 0.7) {
		return CalibrationPercentError;
	}

	for (i=0; i<10; ++i) {
		globals.Flash.os_pwl_amp[channel][0][0][i]=globals.Flash.os_pwl_amp[channel][0][0][i]*change_ratio;
	}


	/* see if new data prevents min/max from being obtained */
	status=Check_MinMax_Cal(channel,pwl_os_values);

	if (status) {
		/* revert to original calibration */
		for (i=0; i<10; ++i) {
			globals.Flash.os_pwl_amp[channel][0][0][i]=globals.Flash.os_pwl_amp[channel][0][0][i]/change_ratio;
		}
	}

	eprom_loc = (char *) &(globals.Flash.os_pwl_amp) - (char *) &(globals.Flash.flash_start);
	writeUserBlock(&globals.Flash, eprom_loc, sizeof(globals.Flash.os_pwl_amp));

	return status;
}


float Get_PW_shift(int channel)
{
	int UseNegData;

	UseNegData = 0;
	if (globals.ChannelState[channel].amplitude < 0.0) {
		UseNegData = 1;
	}

	return globals.Flash.pulse_width_pol_tweak[channel][UseNegData];
}


int Set_PW_shift(int channel,float new_shift)
{
	float orig_shift;
	int UseNegData, status, eprom_loc;

	UseNegData = 0;
	if (globals.ChannelState[channel].amplitude < 0.0) {
		UseNegData = 1;
	}

	orig_shift = globals.Flash.pulse_width_pol_tweak[channel][UseNegData];
	globals.Flash.pulse_width_pol_tweak[channel][UseNegData] = new_shift;

	status=Check_MinMax_Cal(channel,pwl_pw_values);

	if	(status) {
		globals.Flash.pulse_width_pol_tweak[channel][UseNegData] = orig_shift;
		return status;
	}

	eprom_loc = (char *) &(globals.Flash.pulse_width_pol_tweak[channel][UseNegData]) - (char *) &(globals.Flash.flash_start);
	writeUserBlock(&globals.Flash, eprom_loc, sizeof(globals.Flash.pulse_width_pol_tweak[channel][UseNegData]));

	return Set_Pw(0,0,0,channel,globals.ChannelState[channel].pw,0);
}


int Set_Route(int channel, int module, int mode)
{
	int error_num;
	int word_out;

	if (channel && !globals.Flash.ChanKey_route) {
		return InvalidChannel;
	}

	if (!globals.Flash.routing_required[channel]) {
		return Unrecognized;
	}

	if (module >= globals.Flash.routing_required[channel]) {
		return IllegalParameter;
	}

	if ((mode < 1) || (mode > globals.Flash.routing_max_pins[channel])) {
		return OutOfRange;
	}

	int i;
	for (i=0; i<max_channels; ++i) {
		TestState[i]=globals.ChannelState[i];
	}

	if (globals.Flash.routing_max_pins[channel] > 2) {
		if (module == ROUTE_PRIMARY) {
			TestState[channel].route_primary=mode;
			if ((error_num=Error_check(TestState))) {
				return error_num;
			}

			if (mode!=globals.ChannelState[channel].route_primary) {
				globals.ChannelState[channel].route_primary=mode;
			}
		}

		if (module == ROUTE_SECONDARY) {
			TestState[channel].route_secondary=mode;
			if ((error_num=Error_check(TestState))) {
				return error_num;
			}

			if (mode!=globals.ChannelState[channel].route_secondary) {
				globals.ChannelState[channel].route_secondary=mode;
			}
		}
		word_out =  (globals.ChannelState[channel].route_primary-1) |
		            ((globals.ChannelState[channel].route_secondary-1) << 4);
		I2C_Write(PCF8574+Second_PW_Port,word_out);
	} else {
		/* AVD-D2-B */
		if (mode==2) {
			set_shiftreg_bits(SR_2, XTR_POS + 1, ONE_BIT, BIT_HIGH);
		} else {
			set_shiftreg_bits(SR_2, XTR_POS + 1, ONE_BIT, BIT_LOW);
		}
		globals.ChannelState[channel].route_primary=mode;
	}

	Set_Update_Chans();

	return OK;
}


int Set_EO(int channel,int mode)
{
	/* abandon if high channel selected by user but not enabled by firmware */
	if (channel && !globals.Flash.ChanKey_offset) {
		return InvalidChannel;
	}

	if (!globals.Flash.eo_enabled[channel]) {
		return SyntaxError;
	}

	if (globals.ChannelState[channel].os_mode != mode) {
		Set_Offset(0,0,0,0,channel,0.0);
	}

	if (mode) {
		set_shiftreg_bits(SR_2, XTR_POS + 4, ONE_BIT, BIT_HIGH);
	} else {
		set_shiftreg_bits(SR_2, XTR_POS + 4, ONE_BIT, BIT_LOW);
	}

	if (globals.ChannelState[channel].os_mode!=mode) {
		globals.Changes.update_os=YES;
	}

	globals.ChannelState[channel].os_mode=mode;
	Set_Update_Chans();
	Main_update_shift_registers();

	return OK;
}


int Set_Dly_Shr_Nom(int channel,int calibration_point_number)
{
	float temp1, temp2, ampl;

	Main_Rst();
	Main_update_shift_registers();

	Set_frequency(0,0,0,globals.Flash.ChanKey_frequency?channel:0,5.0e0);

	if (globals.Flash.max_ampl[channel] > 0.0) {
		ampl = globals.Flash.max_ampl[channel];
	} else {
		ampl = globals.Flash.min_ampl[channel];
	}
	Set_Amplitude(0,0,0,0,0,0,channel,ampl,0);


	/* Set delay constants to zero, temporarily, for nulling purposes. */
	/* Restore the constants after the delay is set, so that the unit */
	/* will not suffer from an interrupted calibration. */

	temp1=globals.Flash.propagation_delay[channel];
	temp2=globals.Flash.delay_shrink[channel];
	globals.Flash.propagation_delay[channel]=0.0;
	globals.Flash.delay_shrink[channel]=0.0;

	if (calibration_point_number==1) {
		Set_Delay(0,0,0,channel,75e-9);
	} else {
		Set_Delay(0,0,0,channel,-75e-9);
	}

	/* user must set output on, when ready */

	globals.Flash.propagation_delay[channel]=temp1;
	globals.Flash.delay_shrink[channel]=temp2;

	Main_update_shift_registers();

	Show_Main_Menu();

	return OK;
}


int Set_Dly_Shr_Cal(int channel,int calibration_point_number,float cal_point)
{
	int eprom_loc;
	float delay1,delay2;

	delay1=globals.Flash.propagation_delay[channel]-globals.Flash.delay_shrink[channel]+75e-9;
	delay2=globals.Flash.propagation_delay[channel]+globals.Flash.delay_shrink[channel]-75e-9;

	if (calibration_point_number==1) {
		delay1=cal_point;
	} else {
		delay2=cal_point;
	}

	if (delay1>50e-6 || delay2>50e-6) {
		return CalibrationPercentError;
	}

	globals.Flash.propagation_delay[channel]=(delay1+delay2)/2;
	globals.Flash.delay_shrink[channel]=( (150e-9)-delay1+delay2)/2;

	eprom_loc = (char *) &(globals.Flash.propagation_delay) - (char *) &(globals.Flash.flash_start);
	writeUserBlock(&globals.Flash, eprom_loc, sizeof(globals.Flash.propagation_delay));

	eprom_loc = (char *) &(globals.Flash.delay_shrink) - (char *) &(globals.Flash.flash_start);
	writeUserBlock(&globals.Flash, eprom_loc, sizeof(globals.Flash.delay_shrink));

	return OK;
}



int Set_Cal_Nom(int channel,int calibration_point_number,int parameter, float *nom_val)
{
	int nominal_wordout,polarity,range,entry,status,num_in_range,num_of_ranges;
	float nominal_val,other_setting,temp1,temp2;
	int reset_state;
	int disable_errors;
	int true_channel;

	true_channel=channel;

	Get_VI_Rng_Info(parameter,channel,calibration_point_number,&range,&polarity,&entry,&num_in_range,&num_of_ranges);
	status=reset_state=disable_errors=0;

	switch (parameter) {
	case (pwl_ampl_values):
		nominal_val=globals.Flash.ampl_pwl_amp[channel][range][polarity][entry];
		if (polarity) {
			nominal_val=-nominal_val;
		}
		nominal_wordout=globals.Flash.ampl_pwl_Vc_norm4095[channel][range][polarity][entry];
		if (Set_Amplitude(0,0,0,0,0,0,channel,globals.Flash.min_ampl[channel],0) || Set_Amplitude(0,0,0,0,0,0,channel,globals.Flash.max_ampl[channel],0)) {
			/* confirm that timing settings can support min/max ampl settings */
			return CalibrationTimingProblem;
		}
		/* auto-set output impedance, as required */
		if (globals.Flash.switchable_zout[channel]) {
			/* if the cal point is in the top used range, then set Zout to min */
			if (range==num_of_ranges) {
				Set_zout(channel,globals.Flash.zout_min[channel],1);
			} else {
				Set_zout(channel,globals.Flash.zout_max[channel],1);
			}
		}
		break;
	case (pwl_os_values):
		nominal_val=globals.Flash.os_pwl_amp[channel][range][polarity][entry];
		nominal_wordout=globals.Flash.os_pwl_Vc_norm4095[channel][range][polarity][entry];
		break;
	case pwl_pw_values:
		nominal_val=globals.Flash.pw_pwl_time[channel][range][polarity][entry];
		nominal_wordout=globals.Flash.pw_pwl_Vc_norm4095[channel][range][polarity][entry];
		reset_state=disable_errors=1;
		break;
	case pwl_delay_values:
		nominal_val=globals.Flash.delay_pwl_time[channel][range][polarity][entry];
		nominal_wordout=globals.Flash.delay_pwl_Vc_norm4095[channel][range][polarity][entry];
		reset_state=disable_errors=1;
		break;
	case pwl_period_values:
		nominal_val=globals.Flash.period_pwl_time[channel][range][polarity][entry];
		nominal_wordout=globals.Flash.period_pwl_Vc_norm4095[channel][range][polarity][entry];
		reset_state=disable_errors=1;
		break;
	case pwl_burst_values:
		nominal_val=globals.Flash.burst_pwl_time[channel][range][polarity][entry];
		nominal_wordout=globals.Flash.burst_pwl_Vc_norm4095[channel][range][polarity][entry];
		reset_state=disable_errors=1;
		break;
	case pwl_rise_time_values:
		nominal_val=globals.Flash.rise_time_pwl_time[channel][range][polarity][entry];
		nominal_wordout=globals.Flash.rise_time_pwl_Vc_norm4095[channel][range][polarity][entry];
		reset_state=disable_errors=1;
		break;
	case pwl_slew_values:
		nominal_val=globals.Flash.slew_pwl_time[channel][range][polarity][entry];
		nominal_wordout=globals.Flash.slew_pwl_Vc_norm4095[channel][range][polarity][entry];
		break;
	case pwl_vcc1_values:
		nominal_val=globals.Flash.vcc1_pwl_amp[0][0][0][entry];
		nominal_wordout=globals.Flash.vcc1_pwl_Vc_norm4095[0][0][0][entry];
		true_channel=0;
		break;
	case pwl_vcc2_values:
		nominal_val=globals.Flash.vcc2_pwl_amp[0][0][0][entry];
		nominal_wordout=globals.Flash.vcc2_pwl_Vc_norm4095[0][0][0][entry];
		true_channel=0;
		break;
	case pwl_load_type_values:
		nominal_val=globals.Flash.load_type_pwl_time[channel][range][polarity][entry];
		nominal_wordout=globals.Flash.load_type_pwl_Vc_norm4095[channel][range][polarity][entry];
		reset_state=0;
		disable_errors=1;
		break;
	}

	/* just get nominal value, don't activate */
	if (nom_val) {
		*nom_val = nominal_val;
		return OK;
	}

	/* For timing parameters, turn off output and error-checking, and change prf/pw */
	/* For ampl/os parameters, use existing timing and output state, and use error-checking */

	if (reset_state) {
		Main_Rst();
		Set_Output_State(true_channel,output_off);
		Main_update_shift_registers();
		bus_setpin(PW_ENABLE, 1);	/* enable PW circuit (but output relay still off) */
	}

	if (disable_errors) {
		globals.Flash.fully_programmed=Being_Programmed;    /* disable error-checking */
		Ctrl_PRF_Limiter(0);						/* re-enables after *rst */
	}

	globals.Flags.extended_ampl_min_max=YES;
	globals.ChannelState[true_channel].test_delay_mode=NO;

	switch (parameter) {
	case (pwl_ampl_values):
		status=Set_Amplitude(0,polarity,1,nominal_wordout,range,0,channel,nominal_val,0);
		break;
	case (pwl_os_values):
		status=Set_Offset(0,1,nominal_wordout,range,channel,nominal_val);
		break;
	case pwl_pw_values:
		other_setting=0.08/nominal_val;
		if (other_setting > 500e3) {
			other_setting=500e3;
		}

		Set_Pol(channel,pol_norm);

		status=Set_frequency(0,0,0,globals.Flash.ChanKey_frequency?channel:0,other_setting);

		if (!status) {
			status=Set_Pw(0,nominal_wordout,range,channel,nominal_val,0);
		}
		break;
	case pwl_delay_values:
		other_setting=0.08/nominal_val;
		if (other_setting > 500e3) {
			other_setting=500e3;
		}

		/* set delay constants to zero, temporarily */
		temp1=globals.Flash.propagation_delay[channel];
		temp2=globals.Flash.delay_shrink[channel];
		globals.Flash.propagation_delay[channel]=0.0;
		globals.Flash.delay_shrink[channel]=0.0;

		globals.ChannelState[channel].test_delay_mode=YES;

		status=Set_frequency(0,0,0,globals.Flash.ChanKey_frequency?channel:0,other_setting);
		if (!status) {
			status=Set_Delay(0,nominal_wordout,range,channel,nominal_val);
		}

		globals.Flash.propagation_delay[channel]=temp1;
		globals.Flash.delay_shrink[channel]=temp2;

		break;
	case pwl_period_values:
		other_setting=0.4*nominal_val;
		if (other_setting>1.0) {
			other_setting=1.0;    /* reduce pulse width if required */
		}

		status=Set_frequency(0,nominal_wordout,range,channel,1.0/nominal_val);

		if (!status) {
			status=Set_Pw(0,0,0,globals.Flash.ChanKey_pw?channel:0,other_setting,0);
		}
		break;

	case pwl_burst_values:
		other_setting=20.0*nominal_val;

		if (other_setting>10.0) {
			other_setting=10.0;    /* reduce pulse width if required */
		}
		status=Set_frequency(0,0,0,channel,1.0/other_setting);
		Main_update_shift_registers();

		if (!status) {
			status=Set_Pw(0,0,0,globals.Flash.ChanKey_pw?channel:0,nominal_val,0);
		}
		if (!status) {
			status=Set_Burst_Count(channel,4,nominal_val);
		}
		if (!status) {
			status=Set_Burst_Time(0,nominal_wordout,range,channel,nominal_val);
		}

		break;

	case pwl_rise_time_values:
		other_setting=10;	/* reduce test frequency if required */
		status=Set_frequency(0,0,0,globals.Flash.ChanKey_frequency?channel:0,other_setting);
		if (!status) {
			status=Set_rise_time(0,nominal_wordout,range,channel,nominal_val);
		}
		break;

	case pwl_slew_values:
		other_setting=10;	/* reduce test frequency if required */
		status=Set_frequency(0,0,0,globals.Flash.ChanKey_frequency?channel:0,other_setting);
		if (!status) {
			status=Set_slew(0,nominal_wordout,range,channel,nominal_val);
		}
		break;

	case pwl_load_type_values:
		Set_avrq_res(0,nominal_wordout,range,channel,nominal_val);
		break;

	case pwl_vcc1_values:
		status=Set_Amplitude(0,polarity,1,nominal_wordout,range,0,channel,nominal_val,0);
		break;

	case pwl_vcc2_values:
		status=Set_Amplitude(0,polarity,1,nominal_wordout,range,0,channel,nominal_val,0);
		break;

	}

	/* enables or disables delay diagnostic mode */
	Set_Mux(true_channel);

	Main_update_shift_registers();
	Show_Main_Menu();

	/* re-enable error-checking */
	globals.Flash.fully_programmed=All_Programmed;

	/* rise time requires more values to be set before it can be measured */
	if (parameter != pwl_rise_time_values) {
		globals.Flags.extended_ampl_min_max=NO;
	}

	return status;
}


int Set_VI_Cal_Pnt(int parameter,int channel,int calibration_point_number,float cal_point)
{
	int polarity,range,entry,status,num_in_range,num_of_ranges,eprom_loc;
	float nom_ampl;
	int index;
	int max_points,max_polarity,max_ranges;
	float *pwl_amp;
	int true_channel;

	true_channel=channel;

	Get_VI_Rng_Info(parameter,channel,calibration_point_number,&range,&polarity,&entry,&num_in_range,&num_of_ranges);

	max_points=points_in_range;
	switch (parameter) {
	case (pwl_ampl_values):
		max_polarity=ampl_polarities;
		max_ranges=ampl_ranges;
		pwl_amp=&globals.Flash.ampl_pwl_amp[0][0][0][0];
		break;
	case (pwl_os_values):
		max_polarity=os_polarities;
		max_ranges=os_ranges;
		pwl_amp=&globals.Flash.os_pwl_amp[0][0][0][0];
		break;
	case pwl_pw_values:
		max_polarity=timing_polarities;
		max_ranges=timing_ranges;
		pwl_amp=&globals.Flash.pw_pwl_time[0][0][0][0];
		break;
	case pwl_delay_values:
		max_polarity=timing_polarities;
		max_ranges=timing_ranges;
		pwl_amp=&globals.Flash.delay_pwl_time[0][0][0][0];
		break;
	case pwl_period_values:
		max_polarity=timing_polarities;
		max_ranges=timing_ranges;
		pwl_amp=&globals.Flash.period_pwl_time[0][0][0][0];
		break;
	case pwl_burst_values:
		max_polarity=timing_polarities;
		max_ranges=timing_ranges;
		pwl_amp=&globals.Flash.burst_pwl_time[0][0][0][0];
		break;
	case pwl_rise_time_values:
		max_polarity=ampl_polarities;
		max_ranges=ampl_ranges;
		pwl_amp=&globals.Flash.rise_time_pwl_time[0][0][0][0];
		break;
	case pwl_slew_values:
		max_polarity=timing_polarities;
		max_ranges=timing_ranges;
		pwl_amp=&globals.Flash.slew_pwl_time[0][0][0][0];
		break;
	case pwl_vcc1_values:
		max_polarity=1;
		max_ranges=1;
		true_channel=0;
		pwl_amp=&globals.Flash.vcc1_pwl_amp[0][0][0][0];
		break;
	case pwl_vcc2_values:
		max_polarity=1;
		max_ranges=1;
		true_channel=0;
		pwl_amp=&globals.Flash.vcc2_pwl_amp[0][0][0][0];
		break;
	case pwl_load_type_values:
		max_polarity=load_type_polarities;
		max_ranges=load_type_ranges;
		pwl_amp=&globals.Flash.load_type_pwl_time[0][0][0][0];
		break;
	}
	index=true_channel*max_ranges*max_polarity*max_points
	      +range*max_polarity*max_points
	      +polarity*max_points
	      +entry;

	nom_ampl=pwl_amp[index];

	switch (parameter) {
	case (pwl_ampl_values):
		if (globals.ChannelState[channel].amplitude<0.0) {
			nom_ampl=-nom_ampl;
		}
		if ( (cal_point>0.0 && nom_ampl<0.0) || (cal_point<0.0 && nom_ampl>0.0)) {
			return CalibrationPolarityError;
		}
		if (fabs(nom_ampl) < smallest_allowed_number) {
			return CalibrationZeroError;
		}
		if (fabs( (cal_point-nom_ampl)/nom_ampl) >0.3) {
			return CalibrationPercentError;
		}
		break;

	case (pwl_os_values):
		/* check for divide-by-zero error */
		if (fabs(nom_ampl) > smallest_allowed_number) {
			/* exclude relative changes of 30% or more */
			if (fabs( (cal_point-nom_ampl)/nom_ampl) > 0.3) {
				return CalibrationPercentError;
			}
		}
		/* exclude changes greater than 20% of entire range */
		if (fabs(cal_point-nom_ampl) > (0.2*fabs(globals.Flash.max_offset[channel]-globals.Flash.min_offset[channel]))) {
			return CalibrationPercentError;
		}
		break;

	case pwl_pw_values:
	case pwl_period_values:
	case pwl_burst_values:
	case pwl_rise_time_values:
	case pwl_slew_values:
	case pwl_load_type_values:
		/* exclude relative changes of 45% or more unless < 15 ns */
		if ( (fabs(cal_point-nom_ampl)/nom_ampl > 0.45) && (fabs(cal_point-nom_ampl)>15e-9)) {
			return CalibrationPercentError;
		}
		if (cal_point<0.0) {
			return Negative_Not_Allowed;
		}
		break;

	case pwl_delay_values:
		/* exclude relative changes of 45% or more unless < 15 ns */
		if ( (fabs(cal_point-nom_ampl)/nom_ampl > 0.45) && (fabs(cal_point-nom_ampl)>15e-9)) {
			return CalibrationPercentError;
		}
		break;

	case pwl_vcc1_values:
	case pwl_vcc2_values:
		if (fabs(nom_ampl) > smallest_allowed_number) {
			/* exclude relative changes of 30% or more */
			if (fabs( (cal_point-nom_ampl)/nom_ampl) > 0.3) {
				return CalibrationPercentError;
			}
		}
		break;
	}



	status=OK;
	globals.Flags.extended_ampl_min_max=YES;

	if (parameter==pwl_ampl_values) {
		cal_point=fabs(cal_point);
	}

	*(float *)(&pwl_amp[index])=cal_point;

	/* see if new point prevents min/max from being obtained */
	status=Check_MinMax_Cal(channel,parameter);

	if	(status) {
		/* revert to original value if required */
		*(float *)(&pwl_amp[index])=nom_ampl;
	}

	Set_Cal_Nom(channel,calibration_point_number,parameter,NULL);

	Main_update_shift_registers();
	Show_Main_Menu();

	eprom_loc = (char *) (&pwl_amp[index]) - (char *) &(globals.Flash.flash_start);
	writeUserBlock(&globals.Flash, eprom_loc, sizeof(nom_ampl));

	globals.Flags.extended_ampl_min_max=NO;
	return status;
}


int Set_VI_Del_Cal(int parameter,int channel,int calibration_point_number)
{
	int polarity,range,entry,status,i,num_in_range,num_of_ranges;
	float temp1[10];
	short temp2[10];
	int index;
	int max_points,max_polarity,max_ranges;
	short *pointer_short1;
	float *pointer_float1;
	int eprom_loc,size_of_float1,size_of_short1;
	int true_channel;

	true_channel=channel;

	max_points=points_in_range;

	switch (parameter) {
	case (pwl_ampl_values):
		max_polarity=ampl_polarities;
		max_ranges=ampl_ranges;
		pointer_short1=&globals.Flash.ampl_pwl_Vc_norm4095[0][0][0][0];
		pointer_float1=&globals.Flash.ampl_pwl_amp[0][0][0][0];
		size_of_short1=sizeof(globals.Flash.ampl_pwl_Vc_norm4095);
		size_of_float1=sizeof(globals.Flash.ampl_pwl_amp);
		break;
	case (pwl_os_values):
		max_polarity=os_polarities;
		max_ranges=os_ranges;
		pointer_short1=&globals.Flash.os_pwl_Vc_norm4095[0][0][0][0];
		pointer_float1=&globals.Flash.os_pwl_amp[0][0][0][0];
		size_of_short1=sizeof(globals.Flash.os_pwl_Vc_norm4095);
		size_of_float1=sizeof(globals.Flash.os_pwl_amp);
		break;
	case pwl_pw_values:
		max_polarity=timing_polarities;
		max_ranges=timing_ranges;
		pointer_short1=&globals.Flash.pw_pwl_Vc_norm4095[0][0][0][0];
		pointer_float1=&globals.Flash.pw_pwl_time[0][0][0][0];
		size_of_short1=sizeof(globals.Flash.pw_pwl_Vc_norm4095);
		size_of_float1=sizeof(globals.Flash.pw_pwl_time);
		break;
	case pwl_delay_values:
		max_polarity=timing_polarities;
		max_ranges=timing_ranges;
		pointer_short1=&globals.Flash.delay_pwl_Vc_norm4095[0][0][0][0];
		pointer_float1=&globals.Flash.delay_pwl_time[0][0][0][0];
		size_of_short1=sizeof(globals.Flash.delay_pwl_Vc_norm4095);
		size_of_float1=sizeof(globals.Flash.delay_pwl_time);
		break;
	case pwl_period_values:
		max_polarity=timing_polarities;
		max_ranges=timing_ranges;
		pointer_short1=&globals.Flash.period_pwl_Vc_norm4095[0][0][0][0];
		pointer_float1=&globals.Flash.period_pwl_time[0][0][0][0];
		size_of_short1=sizeof(globals.Flash.period_pwl_Vc_norm4095);
		size_of_float1=sizeof(globals.Flash.period_pwl_time);
		break;
	case pwl_burst_values:
		max_polarity=timing_polarities;
		max_ranges=timing_ranges;
		pointer_short1=&globals.Flash.burst_pwl_Vc_norm4095[0][0][0][0];
		pointer_float1=&globals.Flash.burst_pwl_time[0][0][0][0];
		size_of_short1=sizeof(globals.Flash.burst_pwl_Vc_norm4095);
		size_of_float1=sizeof(globals.Flash.burst_pwl_time);
		break;
	case pwl_rise_time_values:
		max_polarity=ampl_polarities;
		max_ranges=ampl_ranges;
		pointer_short1=&globals.Flash.rise_time_pwl_Vc_norm4095[0][0][0][0];
		pointer_float1=&globals.Flash.rise_time_pwl_time[0][0][0][0];
		size_of_short1=sizeof(globals.Flash.rise_time_pwl_Vc_norm4095);
		size_of_float1=sizeof(globals.Flash.rise_time_pwl_time);
		break;
	case pwl_slew_values:
		max_polarity=timing_polarities;
		max_ranges=timing_ranges;
		pointer_short1=&globals.Flash.slew_pwl_Vc_norm4095[0][0][0][0];
		pointer_float1=&globals.Flash.slew_pwl_time[0][0][0][0];
		size_of_short1=sizeof(globals.Flash.slew_pwl_Vc_norm4095);
		size_of_float1=sizeof(globals.Flash.slew_pwl_time);
		break;
	case pwl_vcc1_values:
		max_polarity=1;
		max_ranges=1;
		pointer_short1=&globals.Flash.vcc1_pwl_Vc_norm4095[0][0][0][0];
		pointer_float1=&globals.Flash.vcc1_pwl_amp[0][0][0][0];
		size_of_short1=sizeof(globals.Flash.vcc1_pwl_Vc_norm4095);
		size_of_float1=sizeof(globals.Flash.vcc1_pwl_amp);
		true_channel=0;
		break;
	case pwl_vcc2_values:
		max_polarity=1;
		max_ranges=1;
		pointer_short1=&globals.Flash.vcc2_pwl_Vc_norm4095[0][0][0][0];
		pointer_float1=&globals.Flash.vcc2_pwl_amp[0][0][0][0];
		size_of_short1=sizeof(globals.Flash.vcc2_pwl_Vc_norm4095);
		size_of_float1=sizeof(globals.Flash.vcc2_pwl_amp);
		true_channel=0;
		break;
	case pwl_load_type_values:
		max_polarity=load_type_polarities;
		max_ranges=load_type_ranges;
		pointer_short1=&globals.Flash.load_type_pwl_Vc_norm4095[0][0][0][0];
		pointer_float1=&globals.Flash.load_type_pwl_time[0][0][0][0];
		size_of_short1=sizeof(globals.Flash.load_type_pwl_Vc_norm4095);
		size_of_float1=sizeof(globals.Flash.load_type_pwl_time);
		break;
	}

	Get_VI_Rng_Info(parameter,channel,calibration_point_number,&range,&polarity,&entry,&num_in_range,&num_of_ranges);

	index=true_channel*max_ranges*max_polarity*max_points
	      +range*max_polarity*max_points
	      +polarity*max_points;


	/* can not delete top or bottom of a range */
	if ((entry==0) || (entry==(num_in_range-1))) {
		return CalibrationRangeError;
	}

	/* backup calibration values */
	for (i=0; i<max_points; i++) {
		temp1[i]=pointer_float1[index+i];
		temp2[i]=pointer_short1[index+i];
	}

	/* move the data, overwriting the deleted point */
	for (i=entry; i<max_points-1; i++) {
		*(float *)(&pointer_float1[index+i])=pointer_float1[index+i+1];
		*(short *)(&pointer_short1[index+i])=pointer_short1[index+i+1];
	}

	*(float *)(&pointer_float1[index+points_in_range-1])=0.0;
	*(short *)(&pointer_short1[index+points_in_range-1])=0;

	/* see if new point prevents min/max from being obtained */
	status=Check_MinMax_Cal(channel,parameter);

	if (status) {
		/* revert to original calibration */
		for (i=0; i<max_points; i++) {
			*(float *)(&pointer_float1[index+i])=temp1[i];
			*(short *)(&pointer_short1[index+i])=temp2[i];
		}
	}

	Set_Amplitude(0,0,0,0,0,0,channel,0.0,0);
	Main_update_shift_registers();

	Set_Offset(0,0,0,0,channel,0.0);
	Main_update_shift_registers();

	Show_Main_Menu();

	eprom_loc = (char *) pointer_short1 - (char *) &(globals.Flash.flash_start);
	writeUserBlock(&globals.Flash, eprom_loc, size_of_short1);

	eprom_loc = (char *) pointer_float1 - (char *) &(globals.Flash.flash_start);
	writeUserBlock(&globals.Flash, eprom_loc, size_of_float1);

	return status;
}


int Set_VI_Control(int parameter,int channel,float new_ampl,int *point_found,int *relay_range,int *atten_range,
                   int *UseNegData,int *entry,int *word_out,int *actual_pol)
{
	float use_ampl,tweaked_use_ampl,fraction;
	int i;
	float min_os_in_range,max_os_in_range;
	float min_ampl_in_range,max_ampl_in_range;

	int max_points,max_polarity,max_ranges;
	float *pwl_amp;
	short *pwl_vc;
	int index,use_range;
	int range_i,entry_i;
	float inverse_word_out;
	int timing_extrapolation_allowed;
	int pw_polarity;

	float pw_distort_val;
	float ampl_for_distort_calc;

	int top_range_only;
	int starting_range;

	int decreasing_values_allowed;
	int reciprocal_relationship;

	int true_channel;

	true_channel=channel;

	top_range_only=0;
	starting_range=0;
	max_points=points_in_range;
	timing_extrapolation_allowed=NO;
	reciprocal_relationship=NO;
	decreasing_values_allowed=NO;
	min_os_in_range=max_os_in_range=0.0;
	min_ampl_in_range=max_ampl_in_range=0.0;


	switch (parameter) {
	case pwl_ampl_values:

		if (globals.Flash.ampl_coupled_to_os[channel]) {
			new_ampl+=globals.ChannelState[channel].offset;	/* for 1011-style offset circuit */
		}

		max_polarity=ampl_polarities;
		max_ranges=ampl_ranges;
		pwl_vc=&globals.Flash.ampl_pwl_Vc_norm4095[0][0][0][0];
		pwl_amp=&globals.Flash.ampl_pwl_amp[0][0][0][0];
		if (new_ampl<0.0) {
			*actual_pol=1;
			*UseNegData=1;
		} else {
			*actual_pol=0;
			*UseNegData=0;
		}
		if (globals.Flash.use_pos_ampl_data_only[channel] && new_ampl<0.0) {
			*UseNegData=0;
		}
		use_ampl=fabs(new_ampl);

		/* use top amplitude range in AV-1011 if Zout=2 */
		top_range_only = globals.Flash.switchable_zout[channel]
		                 && (globals.ChannelState[channel].zout==globals.Flash.zout_min[channel]);

		/* if high_impedance_mode the relay range is automatically set to 3 (for 1011, 1015 only),
		   if such a range exists */

		if ( globals.Flash.switchable_load[channel] &&
		                (globals.ChannelState[channel].load_type>globals.Flash.low_load_type[channel]) &&
		                globals.Flash.ampl_pwl_Vc_norm4095[channel][3][*actual_pol][1] > 0) {
			starting_range=3;
			top_range_only=0;
		}

		/* if 1011-OT offset is non-zero, the relay range is automatically set to 3 or 4 (for 1011, 1015 only) */

		if (globals.Flash.ampl_coupled_to_os[channel]
		                && globals.Flash.switchable_zout[channel]
		                && (fabs(globals.ChannelState[channel].offset)>(globals.Flash.max_offset[channel]/max_v_dymanic_range))) {
			starting_range=3;
		}

		/* for AVMP-4-B: lower ampl range used for first PW range only */
		if (globals.Flash.use_high_ampl_ranges_for_high_pw_ranges[channel] &&
		                ((globals.Registers.shift_reg_out[3] & 0x7f) > 0)) {
			top_range_only=1;
		}

		if (globals.Flash.couple_first_N_pw_ranges_to_ampl_ranges[channel]) {
			int curr_pw_range = 0;
			int parse_sr = globals.Registers.shift_reg_out[3] & 0x7f;

			while (parse_sr) {
				++curr_pw_range;
				parse_sr = parse_sr >> 1;
			}

			if (globals.Flash.volt_ctrl_pw[channel]) {
				// ranges are shifted in these units
				++curr_pw_range;
				// except for minimum range
				if (globals.Registers.shift_reg_out[3] & (long)0x01000) {
					curr_pw_range = 0;
				}
			}

			starting_range = curr_pw_range;
			if (starting_range > globals.Flash.couple_first_N_pw_ranges_to_ampl_ranges[channel]) {
				starting_range = globals.Flash.couple_first_N_pw_ranges_to_ampl_ranges[channel];
			}

			top_range_only = 0;
		}

		break;
	case pwl_os_values:
		decreasing_values_allowed=YES;		/* allows Vc=0 to corresponds to most + OS, and Vc=10V to give most - OS */
		max_polarity=os_polarities;
		max_ranges=os_ranges;
		pwl_vc=&globals.Flash.os_pwl_Vc_norm4095[0][0][0][0];
		pwl_amp=&globals.Flash.os_pwl_amp[0][0][0][0];
		*UseNegData=0;
		use_ampl=new_ampl;
		break;
	case pwl_pw_values:
		max_polarity=timing_polarities;
		max_ranges=timing_ranges;
		pwl_vc=&globals.Flash.pw_pwl_Vc_norm4095[0][0][0][0];
		pwl_amp=&globals.Flash.pw_pwl_time[0][0][0][0];
		*UseNegData=0;
		use_ampl=new_ampl;

		/* increase PW if required to compensate for series output diode turn-on time */
		if (		(globals.Flash.fully_programmed != Being_Programmed)
		                &&	(globals.Flash.distort_Y[channel] != 0.0)
		                && (fabs(globals.ChannelState[channel].offset)<fabs(globals.Flash.distort_max_os[channel]))	) {

			ampl_for_distort_calc = fabs(globals.ChannelState[channel].amplitude);

			/* clamping distortion above a certain amplitude */
			if (ampl_for_distort_calc > globals.Flash.distort_max_ampl[channel]) {
				ampl_for_distort_calc = globals.Flash.distort_max_ampl[channel];
			}

			/* clamping distortion below "zero equiv" amplitude */
			if (ampl_for_distort_calc < globals.Flash.ampl_zero_equiv[channel]) {
				ampl_for_distort_calc = globals.Flash.ampl_zero_equiv[channel];
			}

			/* prohit values of Y that would cause divide-by-zero error */
			if ( (-globals.Flash.distort_Y[channel]) > globals.Flash.ampl_zero_equiv[channel]) {
				return PW_Distort_Error;
			}

			pw_distort_val=globals.Flash.distort_Z[channel] +
			               globals.Flash.distort_X[channel] / (ampl_for_distort_calc+globals.Flash.distort_Y[channel]);

			/* calculate new actual PW */
			use_ampl=use_ampl+pw_distort_val;
		}

		/* tweak depending on polarity */
		if (globals.ChannelState[channel].amplitude<0.0) {
			pw_polarity = 1;
			use_ampl=use_ampl+globals.Flash.pulse_width_pol_tweak[channel][pw_polarity];
		} else {
			pw_polarity = 0;
			use_ampl=use_ampl+globals.Flash.pulse_width_pol_tweak[channel][pw_polarity];
		}

		/* tweak depending on amplitude range (steps, not gradual like distort params */

		if (fabs(globals.ChannelState[channel].amplitude) <= globals.Flash.pw_shift_below_this_ampl[channel]) {
			use_ampl=use_ampl+globals.Flash.pw_shift_below_ampl_by[channel];
		}

		reciprocal_relationship=YES;
		timing_extrapolation_allowed=YES;
		break;
	case pwl_delay_values:
		max_polarity=timing_polarities;
		max_ranges=timing_ranges;
		pwl_vc=&globals.Flash.delay_pwl_Vc_norm4095[0][0][0][0];
		pwl_amp=&globals.Flash.delay_pwl_time[0][0][0][0];
		*UseNegData=0;
		use_ampl=new_ampl;
		reciprocal_relationship=YES;
		timing_extrapolation_allowed=YES;
		break;
	case pwl_period_values:
		max_polarity=timing_polarities;
		max_ranges=timing_ranges;
		pwl_vc=&globals.Flash.period_pwl_Vc_norm4095[0][0][0][0];
		pwl_amp=&globals.Flash.period_pwl_time[0][0][0][0];
		*UseNegData=0;
		use_ampl=new_ampl;
		timing_extrapolation_allowed=YES;
		reciprocal_relationship=YES;
		break;
	case pwl_burst_values:
		max_polarity=timing_polarities;
		max_ranges=timing_ranges;
		pwl_vc=&globals.Flash.burst_pwl_Vc_norm4095[0][0][0][0];
		pwl_amp=&globals.Flash.burst_pwl_time[0][0][0][0];
		*UseNegData=0;
		use_ampl=new_ampl;
		reciprocal_relationship=YES;
		timing_extrapolation_allowed=YES;
		break;
	case pwl_rise_time_values:
		max_polarity=ampl_polarities;
		max_ranges=ampl_ranges;
		pwl_vc=&globals.Flash.rise_time_pwl_Vc_norm4095[0][0][0][0];
		pwl_amp=&globals.Flash.rise_time_pwl_time[0][0][0][0];
		if (globals.ChannelState[channel].amplitude<0.0) {
			*actual_pol=*UseNegData=1;
		} else {
			*actual_pol=*UseNegData=0;
		}
		use_ampl=new_ampl;
		reciprocal_relationship=NO;
		timing_extrapolation_allowed=NO;
		break;
	case pwl_slew_values:
		max_polarity=timing_polarities;
		max_ranges=timing_ranges;
		pwl_vc=&globals.Flash.slew_pwl_Vc_norm4095[0][0][0][0];
		pwl_amp=&globals.Flash.slew_pwl_time[0][0][0][0];
		*UseNegData=0;
		use_ampl=new_ampl;
		reciprocal_relationship=NO;
		timing_extrapolation_allowed=NO;
		top_range_only=YES; /* higher drive voltage = lower ripple in slew */
		break;
	case pwl_vcc1_values:
		max_polarity=1;
		max_ranges=1;
		pwl_vc=&globals.Flash.vcc1_pwl_Vc_norm4095[0][0][0][0];
		pwl_amp=&globals.Flash.vcc1_pwl_amp[0][0][0][0];
		*UseNegData=0;
		use_ampl=new_ampl;
		true_channel=0;
		break;
	case pwl_vcc2_values:
		max_polarity=1;
		max_ranges=1;
		pwl_vc=&globals.Flash.vcc2_pwl_Vc_norm4095[0][0][0][0];
		pwl_amp=&globals.Flash.vcc2_pwl_amp[0][0][0][0];
		*UseNegData=0;
		use_ampl=new_ampl;
		true_channel=0;
		break;
	case pwl_load_type_values:
		max_polarity=load_type_polarities;
		max_ranges=load_type_ranges;
		pwl_vc=&globals.Flash.load_type_pwl_Vc_norm4095[0][0][0][0];
		pwl_amp=&globals.Flash.load_type_pwl_time[0][0][0][0];
		*UseNegData=0;
		use_ampl=new_ampl;
		reciprocal_relationship=YES;
		timing_extrapolation_allowed=YES;
		break;
	}



	/* if top_range_only=false, the first match (i.e. in the lowest range) is used. */
	/* if top_range_only=true, the last match (i.e. in the highest range) is used. */

	*point_found=*relay_range=*entry=0;
	*word_out=-1;

	float use_atten = 1.0;

	for (*atten_range = max_attens; (*atten_range >= -1) && !(*point_found);) {

		(*atten_range)--;

		if (*atten_range == -1) {
			// no valid attenuators
			use_atten = 1.0;
		} else {

			if (parameter != pwl_ampl_values) {
				continue;
			} else if (globals.Flash.attenuators[channel][*atten_range] == 0.0) {
				continue;
			} else if (globals.Flags.attenuators_enabled == 0) {
				continue;
			} else {
				use_atten = globals.Flash.attenuators[channel][*atten_range];
			}

			// Limit max voltage in attenuator mode to 93% of full maximum,
			// to avoid the region in AVPs where PW shifts at high amplitudes
			float max1 = fabs(globals.Flash.min_ampl[channel]);
			float max2 = fabs(globals.Flash.max_ampl[channel]);
			if (max2 > max1) {
				max1 = max2;
			}
			if ((use_ampl * use_atten) >
			                (globals.Flash.atten_percent_max_ampl[channel] * max1)) {
				continue;
			}
		}

		for (range_i=starting_range; (range_i<max_ranges) && (!*point_found || top_range_only); ++range_i) {	/* use non-all-zero ranges */
			/* apply pw ampl/pol tweaks */
			if (parameter == pwl_pw_values) {
				// tweak pw shifts
				tweaked_use_ampl = use_ampl + globals.Flash.pw_range_pol_tweaks[channel][range_i][pw_polarity];
			} else if (parameter == pwl_ampl_values) {
				// compensate for attenuators
				tweaked_use_ampl = use_ampl * use_atten;
			} else {
				// no tweaks
				tweaked_use_ampl = use_ampl;
			}

			for (entry_i=0; (entry_i<max_points-1) && (!*point_found || top_range_only); ++entry_i) {
				index=true_channel*max_ranges*max_polarity*max_points
				      +(range_i)*max_polarity*max_points
				      +(*UseNegData)*max_points
				      +(entry_i);

				if ( (fabs(pwl_amp[index]-pwl_amp[index+1])>smallest_allowed_number)
				                &&
				                (	((tweaked_use_ampl>=pwl_amp[index]) &&	(tweaked_use_ampl<=pwl_amp[index+1]))
				                        ||
				                        (decreasing_values_allowed && (tweaked_use_ampl<=pwl_amp[index]) &&	(tweaked_use_ampl>=pwl_amp[index+1]))  /* for OS only */
				                )
				   ) {
					*point_found=1;

					if ((parameter==pwl_ampl_values) && globals.Flash.ampl_os_ranges_related[channel]) {
						for (i=0; i<points_in_range; i++) {
							if (max_os_in_range<globals.Flash.os_pwl_amp[channel][range_i][0][i]) {
								max_os_in_range=globals.Flash.os_pwl_amp[channel][range_i][0][i];
							}
							if (min_os_in_range>globals.Flash.os_pwl_amp[channel][range_i][0][i]) {
								min_os_in_range=globals.Flash.os_pwl_amp[channel][range_i][0][i];
							}
						}
						if ((globals.ChannelState[channel].offset<min_os_in_range) || (globals.ChannelState[channel].offset>max_os_in_range)) {
							*point_found=0;	/* try higher range if can't satisfy os and ampl both in this range */
						}
					}

					if ((parameter==pwl_os_values) && globals.Flash.ampl_os_ranges_related[channel]) {
						for (i=0; i<points_in_range; i++) {
							if (max_ampl_in_range<globals.Flash.ampl_pwl_amp[channel][range_i][*UseNegData][i]) {
								max_ampl_in_range=globals.Flash.ampl_pwl_amp[channel][range_i][*UseNegData][i];
							}
							if (min_ampl_in_range>globals.Flash.ampl_pwl_amp[channel][range_i][*UseNegData][i]) {
								min_ampl_in_range=globals.Flash.ampl_pwl_amp[channel][range_i][*UseNegData][i];
							}
						}
						if ((fabs(globals.ChannelState[channel].amplitude)<min_ampl_in_range) || (fabs(globals.ChannelState[channel].amplitude)>max_ampl_in_range)) {
							*point_found=0;	/* try higher range if can't satisfy os and ampl both in this range */
						}
					}

					fraction = (tweaked_use_ampl-pwl_amp[index]) / (pwl_amp[index] - pwl_amp[index+1]);
					*relay_range=range_i;
					*entry=entry_i;

					/* check for linear voltage-controlled PW */
					if (	(parameter==pwl_pw_values)
					                && globals.Flash.volt_ctrl_pw[channel]
					                && (pwl_vc[index] < pwl_vc[index+1])) {
						reciprocal_relationship=NO;
					}

					if (reciprocal_relationship) {
						inverse_word_out = fraction * (1.0/((float) pwl_vc[index]) - 1.0/((float) pwl_vc[index+1]));
						inverse_word_out+=1/((float) pwl_vc[index]);
						*word_out=(int) (1.0/inverse_word_out);
					} else {
						*word_out = (int) ( fraction * (float) (pwl_vc[index] - pwl_vc[index+1]) );
						*word_out+=pwl_vc[index];
					}
				}
			}
		}
	}

	/* The amplitude/os settings must lie within the calibration points. */
	/* However, the timing data is allowed to lie outside the upper end, */
	/* because the reciprocal relationship allows an asymptotic extension to infinity, */
	/* at the expense of lower resolution */

	if (*word_out<0 && timing_extrapolation_allowed) {
		*point_found=0;
		use_range=-1;

		tweaked_use_ampl = use_ampl;

		/* identify highest range that starts with a cal point less than the setting */
		for (range_i=0; range_i<max_ranges; ++range_i) {	/* use non-all-zero ranges */
			if (parameter == pwl_pw_values) {
				tweaked_use_ampl = use_ampl + globals.Flash.pw_range_pol_tweaks[channel][range_i][pw_polarity];
			}

			index=true_channel*max_ranges*max_polarity*max_points
			      +(range_i)*max_polarity*max_points
			      +(*UseNegData)*max_points;
			if (pwl_amp[index]>smallest_allowed_number && pwl_amp[index]<tweaked_use_ampl) {
				use_range=range_i;
			}
		}

		if (use_range<0) {
			return HardwareError;
		}

		for (entry_i=max_points-2; (entry_i>=0) && (!*point_found); --entry_i) {
			index=true_channel*max_ranges*max_polarity*max_points
			      +(use_range)*max_polarity*max_points
			      +(*UseNegData)*max_points
			      +(entry_i);

			/* find the last two non-zero entries, and extrapolate from them */
			if (		(fabs(pwl_amp[index])>smallest_allowed_number)
			                && (fabs(pwl_amp[index+1])>smallest_allowed_number)
			                && (fabs(pwl_amp[index]-pwl_amp[index+1])>smallest_allowed_number)	) {
				*point_found=1;

				fraction = (tweaked_use_ampl-pwl_amp[index]) / (pwl_amp[index] - pwl_amp[index+1]);
				*relay_range=use_range;
				*entry=entry_i;

				inverse_word_out = fraction * (1.0/((float) pwl_vc[index]) - 1.0/((float) pwl_vc[index+1]));
				inverse_word_out+=1/((float) pwl_vc[index]);
				*word_out=(int) (1.0/inverse_word_out);
			}
		}
	}

	if (*word_out<0) {
		*word_out=0;
		return HardwareError;
	}

	/* check for 12 or 13 bit overflow */
	if (*word_out>dac_max) {
		*word_out=dac_max;	/* just to prevent wandering bits */
		return HardwareError;
	}

	return OK;
}


int Set_VI_Add_Cal(int parameter,int channel,float cal_point)
{
	int point_found,range,polarity,entry,word_out,total,atten_range;
	int i;
	float max_in_range;
	float least_integrated_error,integrated_error;
	float interp_ampl,fraction;
	int delete_point;
	float old_val;
	float abs_cal_point;
	int max_points,max_polarity,max_ranges;

	float temp_y_float[points_in_range+1];
	float temp_x_float[points_in_range+1];
	int temp_x_short[points_in_range+1];

	int index,actual_pol;
	float *pointer_y_float;
	short *pointer_x_short;

	int eprom_loc,size_of_y_float,size_of_x_short;

	int true_channel;

	true_channel = channel;

	range=polarity=0;

	max_points=points_in_range;

	abs_cal_point=cal_point;

	switch (parameter) {
	case (pwl_ampl_values):
		max_polarity=ampl_polarities;
		max_ranges=ampl_ranges;

		pointer_x_short=&globals.Flash.ampl_pwl_Vc_norm4095[0][0][0][0];
		pointer_y_float=&globals.Flash.ampl_pwl_amp[0][0][0][0];
		size_of_x_short=sizeof(globals.Flash.ampl_pwl_Vc_norm4095);
		size_of_y_float=sizeof(globals.Flash.ampl_pwl_amp);

		Set_VI_Control(pwl_ampl_values,channel,globals.ChannelState[channel].amplitude,&point_found,
		               &range,&atten_range,&polarity,&entry,&word_out,&actual_pol);
		old_val=globals.ChannelState[channel].amplitude;
		abs_cal_point=fabs(cal_point);	/* ampl data is positive always */

		/* special amplitude polarity check */

		if ( (cal_point>0.0 && old_val<0.0) || (cal_point<0.0 && old_val>0.0)) {
			return CalibrationPolarityError;
		}

		break;
	case (pwl_os_values):
		max_polarity=os_polarities;
		max_ranges=os_ranges;
		pointer_x_short=&globals.Flash.os_pwl_Vc_norm4095[0][0][0][0];
		pointer_y_float=&globals.Flash.os_pwl_amp[0][0][0][0];
		size_of_x_short=sizeof(globals.Flash.os_pwl_Vc_norm4095);
		size_of_y_float=sizeof(globals.Flash.os_pwl_amp);

		old_val=globals.ChannelState[channel].offset;
		Set_VI_Control(pwl_os_values,channel,old_val,&point_found,
		               &range,&atten_range,&polarity,&entry,&word_out,&actual_pol);
		break;
	case pwl_pw_values:
		max_polarity=timing_polarities;
		max_ranges=timing_ranges;
		pointer_x_short=&globals.Flash.pw_pwl_Vc_norm4095[0][0][0][0];
		pointer_y_float=&globals.Flash.pw_pwl_time[0][0][0][0];
		size_of_x_short=sizeof(globals.Flash.pw_pwl_Vc_norm4095);
		size_of_y_float=sizeof(globals.Flash.pw_pwl_time);
		old_val=globals.ChannelState[channel].pw;
		Set_VI_Control(pwl_pw_values,channel,old_val,&point_found,
		               &range,&atten_range,&polarity,&entry,&word_out,&actual_pol);
		break;
	case pwl_delay_values:
		max_polarity=timing_polarities;
		max_ranges=timing_ranges;
		pointer_x_short=&globals.Flash.delay_pwl_Vc_norm4095[0][0][0][0];
		pointer_y_float=&globals.Flash.delay_pwl_time[0][0][0][0];
		size_of_x_short=sizeof(globals.Flash.delay_pwl_Vc_norm4095);
		size_of_y_float=sizeof(globals.Flash.delay_pwl_time);
		old_val=globals.ChannelState[channel].delay;
		Set_VI_Control(pwl_delay_values,channel,old_val,&point_found,
		               &range,&atten_range,&polarity,&entry,&word_out,&actual_pol);
		break;
	case pwl_period_values:
		max_polarity=timing_polarities;
		max_ranges=timing_ranges;
		pointer_x_short=&globals.Flash.period_pwl_Vc_norm4095[0][0][0][0];
		pointer_y_float=&globals.Flash.period_pwl_time[0][0][0][0];
		size_of_x_short=sizeof(globals.Flash.period_pwl_Vc_norm4095);
		size_of_y_float=sizeof(globals.Flash.period_pwl_time);
		old_val=1.0/globals.ChannelState[channel].frequency;
		Set_VI_Control(pwl_period_values,channel,old_val,&point_found,
		               &range,&atten_range,&polarity,&entry,&word_out,&actual_pol);
		break;
	case pwl_burst_values:
		max_polarity=timing_polarities;
		max_ranges=timing_ranges;
		pointer_x_short=&globals.Flash.burst_pwl_Vc_norm4095[0][0][0][0];
		pointer_y_float=&globals.Flash.burst_pwl_time[0][0][0][0];
		size_of_x_short=sizeof(globals.Flash.burst_pwl_Vc_norm4095);
		size_of_y_float=sizeof(globals.Flash.burst_pwl_time);
		old_val=globals.ChannelState[channel].burst_time;
		Set_VI_Control(pwl_burst_values,channel,old_val,&point_found,
		               &range,&atten_range,&polarity,&entry,&word_out,&actual_pol);
		break;
	case pwl_rise_time_values:
		max_polarity=ampl_polarities;
		max_ranges=ampl_ranges;
		pointer_x_short=&globals.Flash.rise_time_pwl_Vc_norm4095[0][0][0][0];
		pointer_y_float=&globals.Flash.rise_time_pwl_time[0][0][0][0];
		size_of_x_short=sizeof(globals.Flash.rise_time_pwl_Vc_norm4095);
		size_of_y_float=sizeof(globals.Flash.rise_time_pwl_time);
		old_val=globals.ChannelState[channel].rise_time;
		Set_VI_Control(pwl_rise_time_values,channel,old_val,&point_found,
		               &range,&atten_range,&polarity,&entry,&word_out,&actual_pol);
		break;
	case pwl_slew_values:
		max_polarity=timing_polarities;
		max_ranges=timing_ranges;
		pointer_x_short=&globals.Flash.slew_pwl_Vc_norm4095[0][0][0][0];
		pointer_y_float=&globals.Flash.slew_pwl_time[0][0][0][0];
		size_of_x_short=sizeof(globals.Flash.slew_pwl_Vc_norm4095);
		size_of_y_float=sizeof(globals.Flash.slew_pwl_time);
		old_val=globals.ChannelState[channel].slew;
		Set_VI_Control(pwl_slew_values,channel,old_val,&point_found,
		               &range,&atten_range,&polarity,&entry,&word_out,&actual_pol);
		break;
	case pwl_vcc1_values:
		max_polarity=1;
		max_ranges=1;
		true_channel=0;
		pointer_x_short=&globals.Flash.vcc1_pwl_Vc_norm4095[0][0][0][0];
		pointer_y_float=&globals.Flash.vcc1_pwl_amp[0][0][0][0];
		size_of_x_short=sizeof(globals.Flash.vcc1_pwl_Vc_norm4095);
		size_of_y_float=sizeof(globals.Flash.vcc1_pwl_amp);
		old_val=globals.ChannelState[true_channel].vcc1;
		Set_VI_Control(pwl_vcc1_values,channel,old_val,&point_found,
		               &range,&atten_range,&polarity,&entry,&word_out,&actual_pol);
		break;
	case pwl_vcc2_values:
		max_polarity=1;
		max_ranges=1;
		true_channel=0;
		pointer_x_short=&globals.Flash.vcc2_pwl_Vc_norm4095[0][0][0][0];
		pointer_y_float=&globals.Flash.vcc2_pwl_amp[0][0][0][0];
		size_of_x_short=sizeof(globals.Flash.vcc2_pwl_Vc_norm4095);
		size_of_y_float=sizeof(globals.Flash.vcc2_pwl_amp);
		old_val=globals.ChannelState[true_channel].vcc2;
		Set_VI_Control(pwl_vcc2_values,channel,old_val,&point_found,
		               &range,&atten_range,&polarity,&entry,&word_out,&actual_pol);
		break;
	case pwl_load_type_values:
		max_polarity=load_type_polarities;
		max_ranges=load_type_ranges;
		pointer_x_short=&globals.Flash.load_type_pwl_Vc_norm4095[0][0][0][0];
		pointer_y_float=&globals.Flash.load_type_pwl_time[0][0][0][0];
		size_of_x_short=sizeof(globals.Flash.load_type_pwl_Vc_norm4095);
		size_of_y_float=sizeof(globals.Flash.load_type_pwl_time);
		old_val=globals.ChannelState[channel].load_type;
		Set_VI_Control(pwl_load_type_values,channel,old_val,&point_found,
		               &range,&atten_range,&polarity,&entry,&word_out,&actual_pol);
		break;

	}

	temp_y_float[max_points]=0.0;		/* Adding a cal point may temporarily result in 11 data points. */
	temp_x_float[max_points]=0.0;		/* One is eventually discarded. */
	temp_x_short[max_points]=0;


	index=true_channel*max_ranges*max_polarity*max_points
	      +range*max_polarity*max_points
	      +polarity*max_points;


	/* make a copy of the calibration data in this range */
	for (i=0; i<max_points; i++) {
		temp_y_float[i]=pointer_y_float[index+i];		/* work on this data */
		temp_x_short[i]=pointer_x_short[index+i];
	}


	/* check range for maximum value, and number of points */
	max_in_range=0.0;
	total=max_points;
	for (i=max_points-1; i>=0; --i) {
		if ( 	fabs(temp_y_float[i])<smallest_allowed_number && (total==i+1)) {
			--total;
		}
		if (fabs(temp_y_float[i])>max_in_range) {
			max_in_range=fabs(temp_y_float[i]);
		}
	}


	/*	check for excessive deviation between old and new amplitudes at this range/word combination */
	if (fabs(cal_point-old_val) > max_in_range/3.0) {
		return CalibrationPercentError;
	}
	/* check for overly-close data points */
	if ( word_out==temp_x_short[entry] ) {
		return CalibrationClosenessError;
	}
	if ( word_out==temp_x_short[entry+1]) {
		return CalibrationClosenessError;
	}



	/* move old data over */
	for (i=max_points-1; i>entry; i--) {
		temp_y_float[i+1]=temp_y_float[i];
		temp_x_short[i+1]=temp_x_short[i];
	}


	/*	add the new data */
	temp_y_float[entry+1]=abs_cal_point;
	temp_x_short[entry+1]=word_out;
	for (i=0; i<=max_points; ++i) {
		temp_x_float[i]=(float) temp_x_short[i];
	}


	/* delete a point, if required */
	if (total==max_points) {
		least_integrated_error=1e18;

		for (i=1; i<max_points; i++) {	/* end points are not considered for deletion */
			/* calculate interpolated amplitude, if this cal point was deleted */
			fraction = 	(temp_x_float[i]-temp_x_float[i-1]) / (temp_x_float[i+1]-temp_x_float[i-1]);
			interp_ampl = temp_y_float[i-1] + (fraction * (temp_y_float[i+1]-temp_y_float[i-1]));

			/* calculate percent error at interpolated point */
			integrated_error = fabs( (interp_ampl-temp_y_float[i])/temp_y_float[i]);

			/* calculate intergrated error */
			integrated_error *= fabs( temp_y_float[i+1] - temp_y_float[i-1] );

			if (integrated_error<least_integrated_error) {
				delete_point=i;
				least_integrated_error=integrated_error;
			}
		}

		/* delete the point that is most linear with the two around it */
		for (i=delete_point; i<max_points; i++) {
			temp_y_float[i]=temp_y_float[i+1];
			temp_x_float[i]=temp_x_float[i+1];
			temp_x_short[i]=temp_x_short[i+1];
		}
	}


	/* store new calibration data for this range */
	for (i=0; i<max_points; i++) {
		*(float *)(&pointer_y_float[index+i])=temp_y_float[i];
		*(short *)(&pointer_x_short[index+i])=temp_x_short[i];
	}

	eprom_loc = (char *) pointer_x_short - (char *) &(globals.Flash.flash_start);
	writeUserBlock(&globals.Flash, eprom_loc, size_of_x_short);

	eprom_loc = (char *) pointer_y_float - (char *) &(globals.Flash.flash_start);
	writeUserBlock(&globals.Flash, eprom_loc, size_of_y_float);

	globals.Flags.extended_ampl_min_max=NO;

	/* update output */
	switch (parameter) {
	case (pwl_ampl_values):
	case (pwl_vcc1_values):
	case (pwl_vcc2_values):
		Set_Amplitude(0,0,0,0,0,0,channel,cal_point,0);
		break;

	case (pwl_os_values):
		Set_Offset(0,0,0,0,channel,cal_point);
		break;

	case pwl_pw_values:
		Set_Pw(0,0,0,channel,cal_point,0);
		break;

	case pwl_delay_values:
		Set_Delay(0,0,0,channel,cal_point);
		break;

	case pwl_period_values:
		Set_frequency(0,0,0,channel,cal_point);
		break;

	case pwl_burst_values:
		Set_Burst_Time(0,0,0,channel,cal_point);
		break;

	case pwl_rise_time_values:
		Set_rise_time(0,0,0,channel,cal_point);
		break;

	case pwl_slew_values:
		Set_slew(0,0,0,channel,cal_point);
		break;

	case pwl_load_type_values:
		Set_avrq_res(0,0,0,channel,cal_point);
		break;
	}

	return OK;
}


int Get_VI_Num_Pnts(int parameter,int channel)
{
	int dummy1,dummy2,dummy3,num_in_range,num_of_ranges;

	return Get_VI_Rng_Info(parameter,channel,0,&dummy1,&dummy2,&dummy3,&num_in_range,&num_of_ranges);
}



int Get_VI_Rng_Info(int parameter, int channel, int calibration_point_number, int *range,
                    int *polarity, int *entry, int *num_in_range, int *num_of_ranges)
{
	int x_polarity,x_range,x_entry,total;
	int num_in_current_range;
	int max_polarity,max_points,max_ranges;
	float *pwl;
	int index;
	int true_channel;

	true_channel=channel;

	*polarity=0;
	*range=0;
	*entry=0;
	*num_in_range=0;

	/* determine array structure */
	max_points=points_in_range;

	switch (parameter) {
	case pwl_ampl_values:
		max_polarity=ampl_polarities;
		max_ranges=ampl_ranges;
		pwl=&globals.Flash.ampl_pwl_amp[0][0][0][0];
		break;
	case pwl_os_values:
		max_polarity=os_polarities;
		max_ranges=os_ranges;
		pwl=&globals.Flash.os_pwl_amp[0][0][0][0];
		break;
	case pwl_pw_values:
		max_polarity=timing_polarities;
		max_ranges=timing_ranges;
		pwl=&globals.Flash.pw_pwl_time[0][0][0][0];
		break;
	case pwl_delay_values:
		max_polarity=timing_polarities;
		max_ranges=timing_ranges;
		pwl=&globals.Flash.delay_pwl_time[0][0][0][0];
		break;
	case pwl_period_values:
		max_polarity=timing_polarities;
		max_ranges=timing_ranges;
		pwl=&globals.Flash.period_pwl_time[0][0][0][0];
		break;
	case pwl_burst_values:
		max_polarity=timing_polarities;
		max_ranges=timing_ranges;
		pwl=&globals.Flash.burst_pwl_time[0][0][0][0];
		break;
	case pwl_rise_time_values:
		max_polarity=ampl_polarities;
		max_ranges=ampl_ranges;
		pwl=&globals.Flash.rise_time_pwl_time[0][0][0][0];
		break;
	case pwl_slew_values:
		max_polarity=timing_polarities;
		max_ranges=timing_ranges;
		pwl=&globals.Flash.slew_pwl_time[0][0][0][0];
		break;
	case pwl_vcc1_values:
		max_polarity=1;
		max_ranges=1;
		pwl=&globals.Flash.vcc1_pwl_amp[0][0][0][0];
		true_channel=0;
		break;
	case pwl_vcc2_values:
		max_polarity=1;
		max_ranges=1;
		pwl=&globals.Flash.vcc2_pwl_amp[0][0][0][0];
		true_channel=0;
		break;
	case pwl_load_type_values:
		max_polarity=load_type_polarities;
		max_ranges=load_type_ranges;
		pwl=&globals.Flash.load_type_pwl_time[0][0][0][0];
		break;
	}



	total=0;
	*num_of_ranges=0;

	for (x_polarity=0; x_polarity<max_polarity; x_polarity++)
		for (x_range=0; x_range<max_ranges; x_range++) {

			/* determine number of data points in range */
			/* do this by counting number of zeroes at top end of array */
			num_in_current_range=max_points;
			for (x_entry=max_points-1; x_entry>=0; --x_entry) {
				/* pwl is a pointer to either the amplitude or offset control array. */
				/* Multidimensional pointer arrays are not possible, since the array size */
				/* is unknown at compilation time. Thus, the index offset has to be calculated manually. */
				index=true_channel*max_ranges*max_polarity*max_points
				      +x_range*max_polarity*max_points
				      +x_polarity*max_points
				      +x_entry;
				if ( 	fabs(pwl[index])<smallest_allowed_number && (num_in_current_range==x_entry+1)) {
					--num_in_current_range;
				}
			}

			if (num_in_current_range) {
				*num_of_ranges=x_range;

				for (x_entry=0; x_entry<num_in_current_range; x_entry++) {
					++total;
					if (total==calibration_point_number) {
						calibration_point_number=0;  /* to prevent further matches */
						*range=x_range;
						*polarity=x_polarity;
						*entry=x_entry;
						*num_in_range=num_in_current_range;
					}
				}
			}
		}

	return total;
}


int Check_MinMax_Cal(int channel,int parameter)
{
	int status;

	status=OK;

	/* see if new point prevents zero, min, max, or current value from being obtained */
	switch (parameter) {
	case (pwl_ampl_values):
		status=Set_Amplitude(1,0,0,0,0,0,channel,globals.Flash.min_ampl[channel],0)
		       || Set_Amplitude(1,0,0,0,0,0,channel,globals.Flash.max_ampl[channel],0)
		       || Set_Amplitude(1,0,0,0,0,0,channel,0.0,0);
		break;

	case (pwl_os_values):
		status=Set_Offset(1,0,0,0,channel,globals.Flash.min_offset[channel])
		       || Set_Offset(1,0,0,0,channel,globals.Flash.max_offset[channel])
		       || Set_Offset(1,0,0,0,channel,0.0);
		break;

	case pwl_pw_values:
		status=Set_Pw(1,0,0,channel,globals.Flash.min_pw[channel],0)
		       || Set_Pw(1,0,0,channel,globals.Flash.max_pw[channel],0);
		break;

	case pwl_delay_values:
		status=Set_Delay(1,0,0,channel,globals.Flash.min_delay[channel])
		       || Set_Delay(1,0,0,channel,globals.Flash.max_delay[channel]);
		break;

	case pwl_period_values:
		status=Set_frequency(1,0,0,channel,globals.Flash.min_freq[channel])
		       || Set_frequency(1,0,0,channel,globals.Flash.max_freq[channel]);
		break;

	case pwl_burst_values:
		status=Set_Burst_Time(1,0,0,channel,globals.Flash.min_burst_gap[channel])
		       || Set_Burst_Time(1,0,0,channel,globals.Flash.max_burst_gap[channel]);
		break;

	case pwl_rise_time_values:
		status=Set_rise_time(1,0,0,channel,globals.Flash.min_rise_time[channel])
		       || Set_rise_time(1,0,0,channel,globals.Flash.max_rise_time[channel]);
		break;

	case pwl_slew_values:
		status=Set_slew(1,0,0,channel,globals.Flash.min_slew[channel])
		       || Set_slew(1,0,0,channel,globals.Flash.max_slew[channel]);
		break;

	case (pwl_vcc1_values):
		status=Set_Amplitude(1,0,0,0,0,0,channel,0.0,0)
		       || Set_Amplitude(1,0,0,0,0,0,channel,globals.Flash.vcc1_max[0],0);
		break;

	case (pwl_vcc2_values):
		status=Set_Amplitude(1,0,0,0,0,0,channel,0.0,0)
		       || Set_Amplitude(1,0,0,0,0,0,channel,globals.Flash.vcc2_max[0],0);
		break;

	case pwl_load_type_values:
		status=Set_avrq_res(1,0,0,channel,globals.Flash.low_load_type[channel])
		       || Set_avrq_res(1,0,0,channel,globals.Flash.high_load_type[channel]);
		break;
	}

	if (status) {
		/* change the error code to a calibration-related one */
		status=CalibrationMinMaxError;
	}

	return status;
}


int control_pcb107(int address, int dac, int word, int range)
{
	/* reset all lines */
	I2C_Write(PCF8574+address,0);

	set_dac(dac,word);

	/* send and load range data */
	I2C_Write(PCF8574+address,(range << 3));
	I2C_Write(PCF8574+address,(range << 3) | 0x80);

	/* clear the lines */
	I2C_Write(PCF8574+address,0);

	return OK;
}


int Set_Burst_Count(int channel,int count,float new_burst_time)
{
	int check_valid;

	if (globals.Flash.max_burst_count[channel]<=1) {
		return Unrecognized;
	}

	/* abandon if high channel selected by user but not enabled by firmware */
	if (channel && !globals.Flash.ChanKey_Burst_Count) {
		return InvalidChannel;
	}

	/* check duty cycle */
	int i;
	for (i=0; i<max_channels; ++i) {
		TestState[i]=globals.ChannelState[i];
	}
	TestState[channel].burst_count=count;
	if ((check_valid=Error_check(TestState))) {
		return check_valid;
	}

	globals.ChannelState[channel].burst_count = count;
	Set_Update_Chans();

	if (!globals.Flash.burst_func[channel]) {
		/* Call update routine for pulse generator burst mode. */
		/* Update pulse separation at the same time. This routine does the actual changes. */
		Set_Burst_Time(0,0,0,channel,new_burst_time);
	} else {
		int hextext_out;

		/* reset all lines */
		I2C_Write(PCF8574+Second_PW_Port,0);

		/* send first hextet */
		hextext_out=globals.ChannelState[channel].burst_count & 0x003f;

		I2C_Write(PCF8574+Second_PW_Port, hextext_out);
		/* load hextet */
		I2C_Write(PCF8574+Second_PW_Port, hextext_out | 0x40 );

		/* send second hextet */
		if (globals.ChannelState[channel].burst_count > 0) {
			/* set "not_reset" bit high to enable burst mode for N > 0 */
			hextext_out = ((globals.ChannelState[channel].burst_count >> 6) & 0x07) | 0x08;
		} else {
			hextext_out = 0;
		}

		I2C_Write(PCF8574+Second_PW_Port, hextext_out);
		/* load hextet */
		I2C_Write(PCF8574+Second_PW_Port, hextext_out | 0x80 );

		/* clear the lines */
		I2C_Write(PCF8574+Second_PW_Port,0);

	}

	return OK;
}


int Set_Burst_Time(int check_possible_only,int word_override,int range_override,int channel,float new_burst_time)
{
	int count_word_out;
	int point_found,relay_range,UseNegData,entry,actual_pol,word_out,dummy;

	if (globals.Flash.max_burst_count[channel]<=1) {
		return Unrecognized;
	}

	/* abandon if high channel selected by user but not enabled by firmware */
	if (channel && !globals.Flash.ChanKey_Burst_Time) {
		return InvalidChannel;
	}

	if (!check_possible_only) {
		/* check duty cycle */
		int i, check_valid;
		for (i=0; i<max_channels; ++i) {
			TestState[i]=globals.ChannelState[i];
		}
		TestState[channel].burst_time=new_burst_time;
		if ((check_valid=Error_check(TestState))) {
			return check_valid;
		}
	}

	/* tweak count based on actual circuit */
	count_word_out = globals.ChannelState[channel].burst_count - 1;

	/* find appropriate range/fine settings from piece-wise linear data in flash memory */
	if (word_override) {
		word_out=word_override;
		relay_range=range_override;
	} else {
		int status;
		if ((status=Set_VI_Control(pwl_burst_values,channel,new_burst_time,&point_found,
		                           &relay_range,&dummy,&UseNegData,&entry,&word_out,&actual_pol))) {
			return status;
		}
	}

	if (check_possible_only) {
		if (point_found) {
			return OK;
		} else {
			return CalibrationMinMaxError;
		}
	}

	start_gate_override ();

	/* update DAC */
	set_dac(6,word_out);


	/* update range and burst count */

	/* reset all lines */
	I2C_Write(PCF8574+Second_PW_Port,0);

	/* send first hextet */
	int hextext_out=count_word_out & 0x003f;

	I2C_Write(PCF8574+Second_PW_Port, hextext_out);
	/* load hextet */
	I2C_Write(PCF8574+Second_PW_Port, hextext_out | 0x40 );

	/* send second hextet */
	hextext_out=	((count_word_out >> 6) & 0x07) | ((relay_range	 << 3) & 0x0038);

	I2C_Write(PCF8574+Second_PW_Port, hextext_out);
	/* load hextet */
	I2C_Write(PCF8574+Second_PW_Port, hextext_out | 0x80 );

	/* clear the lines */
	I2C_Write(PCF8574+Second_PW_Port,0);

	if (globals.Registers.last_relay_driver_settings[2] != relay_range) {
		g_usleep (1e3 * globals.Timers.normal_relay_bounce_time_in_milliseconds);
	}
	stop_gate_override ();

	globals.Registers.last_relay_driver_settings[2] = relay_range;

	globals.ChannelState[channel].burst_time = new_burst_time;

	Set_Update_Chans();

	return OK;
}


int Set_rise_time(int check_possible_only,int word_override,int range_override,int channel,float new_rise_time)
{
	int point_found,relay_range,UseNegData,entry,actual_pol,word_out,dummy;
	char range_control;

	if (globals.Flash.fixed_rise_time[channel]) {
		return Unrecognized;
	}

	/* abandon if high channel selected by user but not enabled by firmware */
	if (channel && !globals.Flash.ChanKey_rise_time) {
		return InvalidChannel;
	}

	if (!check_possible_only) {
		/* check duty cycle */
		int i, check_valid;
		for (i=0; i<max_channels; ++i) {
			TestState[i]=globals.ChannelState[i];
		}
		TestState[channel].rise_time=new_rise_time;
		if ((check_valid=Error_check(TestState))) {
			return check_valid;
		}
	}

	/* find appropriate range/fine settings from piece-wise linear data in flash memory */
	if (word_override) {
		word_out=word_override;
		relay_range=range_override;
	} else {
		int status;
		if ((status=Set_VI_Control(pwl_rise_time_values,channel,new_rise_time,&point_found,
		                           &relay_range,&dummy,&UseNegData,&entry,&word_out,&actual_pol))) {
			return status;
		}
	}

	if (check_possible_only) {
		if (point_found) {
			return OK;
		} else {
			return CalibrationMinMaxError;
		}
	}

	set_dac(globals.Flash.rise_time_dac[channel],word_out);

	if (!globals.Flash.pcb_203a_rise_time[channel]) {
		/* original AVRQ PCB */
		switch (relay_range) {
		case 0:
			range_control = (char) 0x01;
			break;
		case 1:
			range_control = (char) 0x08;
			break;
		case 2:
			range_control = (char) 0x10;
			break;
		case 3:
			range_control = (char) 0x20;
			break;
		case 4:
			range_control = (char) 0x40;
			break;
		case 5:
			range_control = (char) 0x80;
			break;
		case 6:
		case 7:
			return HardwareError;
			break;
		}
	} else {
		/* PCB 203A */
		switch (relay_range) {
		case 0:
			range_control = (char) 0x0f;
			break;
		case 1:
			range_control = (char) 0x02;
			break;
		case 2:
			range_control = (char) 0x04;
			break;
		case 3:
			range_control = (char) 0x08;
			break;
		case 4:
			range_control = (char) 0x10;
			break;
		case 5:
		case 6:
		case 7:
			return HardwareError;
			break;
		}
	}



	if (globals.Registers.last_rise_time_relay_setting != range_control) {
		/* update range hardware */
		if (globals.ChannelState[channel].trigger_source!=source_hold) {
			bus_setpin(O_GATE, 1);
		}

		if (!globals.Flash.pcb_203a_rise_time[channel]) {
			I2C_Write(PCF8574A+rise_time_port,range_control);
		} else {
			globals.Registers.avrq_reg = (range_control & 0x1f) |
			                             (globals.Registers.avrq_reg & 0xe0);
			I2C_Write(PCF8574A+rise_time_port,globals.Registers.avrq_reg);
		}
		g_usleep (5e5);

		if (globals.ChannelState[channel].trigger_source!=source_hold) {
			bus_setpin(O_GATE, 0);
		}
	}

	globals.ChannelState[channel].rise_time = new_rise_time;
	globals.Registers.last_rise_time_relay_setting = range_control;

	Set_Update_Chans();

	return OK;
}


int Set_current_limit(int check_possible_only,int channel,float new_adj_current_limit)
{
	float limit;
	int word_out;

	if (!globals.Flash.hard_current_limit_enabled[channel]) {
		return Unrecognized;
	}

	/* abandon if high channel selected by user but not enabled by firmware */
	if (channel && !globals.Flash.ChanKey_current_limit) {
		return InvalidChannel;
	}

	if (!check_possible_only) {
		int i, check_valid;
		for (i=0; i<max_channels; ++i) {
			TestState[i]=globals.ChannelState[i];
		}
		TestState[channel].soft_current_limit=new_adj_current_limit;
		if ((check_valid=Error_check(TestState))) {
			return check_valid;
		}
	}

	if (globals.ChannelState[channel].func_mode==dc_mode_on) {
		limit=globals.Flash.current_limit_dc_mode[channel];
	} else {
		limit=globals.Flash.current_limit_pulse_mode[channel];
	}

	if (globals.Flash.soft_current_limit_enabled[channel] && (new_adj_current_limit<limit)) {
		limit=new_adj_current_limit;
	}

	word_out = (int) ( ((float) dac_max) * (limit/globals.Flash.current_limit_full_scale[channel]) );
	set_dac(globals.Flash.current_limit_dac[channel],word_out);

	globals.ChannelState[channel].soft_current_limit=limit;

	return OK;
}


int Set_avrq_res(int check_possible_only,int word_override,int range_override,int channel,float new_res)
{
	int point_found,relay_range,UseNegData,entry,actual_pol,word_out,dummy;

	if (!globals.Flash.switchable_load[channel]) {
		return Unrecognized;
	}

	/* abandon if high channel selected by user but not enabled by firmware */
	if (channel && !globals.Flash.ChanKey_load_type) {
		return InvalidChannel;
	}

	if (!check_possible_only) {
		int i, check_valid;

		for (i=0; i<max_channels; ++i) {
			TestState[i]=globals.ChannelState[i];
		}
		TestState[channel].load_type=new_res;
		if ((check_valid=Error_check(TestState))) {
			return check_valid;
		}
	}

	/* find appropriate range/fine settings from piece-wise linear data in flash memory */
	if (word_override) {
		word_out=word_override;
		relay_range=range_override;
	} else {
		/* ugly hack - fix me?
		   CH2 = opto VCC
		   Calibrate res at 3.0V
		   Compensate for >3.0V */
		float compensated_new_res;

		if (globals.ChannelState[0].vcc2 > 0.0) {
			compensated_new_res = new_res * 3.0/globals.ChannelState[0].vcc2;
		} else {
			return amplitude_lower_limit;
		}

		int status;
		if ((status=Set_VI_Control(pwl_load_type_values,channel,compensated_new_res,&point_found,
		                           &relay_range,&dummy,&UseNegData,&entry,&word_out,&actual_pol))) {
			return status;
		}
	}

	if (check_possible_only) {
		if (point_found) {
			return OK;
		} else {
			return CalibrationMinMaxError;
		}
	}

	set_dac(globals.Flash.load_type_dac[channel],word_out);

	/* no ranges are used */

	/* update variables if OK */
	if (new_res!=globals.ChannelState[channel].load_type) {
		globals.Changes.update_load=YES;
	}

	globals.ChannelState[channel].load_type = new_res;

	Set_Update_Chans();

	return OK;
}


int Set_slew(int check_possible_only,int word_override,int range_override,int channel,float new_slew)
{
	int check_valid;
	int status,point_found,relay_range,UseNegData,entry,actual_pol,word_out,dummy;
	char range_control;

	if (!globals.Flash.curr_slew[channel]) {
		return Unrecognized;
	}

	/* abandon if high channel selected by user but not enabled by firmware */
	if (channel && !globals.Flash.ChanKey_slew) {
		return InvalidChannel;
	}

	if (!check_possible_only) {
		/* check duty cycle */
		int i;
		for (i=0; i<max_channels; ++i) {
			TestState[i]=globals.ChannelState[i];
		}
		TestState[channel].slew=new_slew;
		if ((check_valid=Error_check(TestState))) {
			return check_valid;
		}
	}

	/* find appropriate range/fine settings from piece-wise linear data in flash memory */
	if (word_override) {
		word_out=word_override;
		relay_range=range_override;
	} else {
		if ((status=Set_VI_Control(pwl_slew_values,channel,new_slew,&point_found,
		                           &relay_range,&dummy,&UseNegData,&entry,&word_out,&actual_pol))) {
			return status;
		}
	}

	if (check_possible_only) {
		if (point_found) {
			return OK;
		} else {
			return CalibrationMinMaxError;
		}
	}

	set_dac(globals.Flash.slew_dac[channel],word_out);

	switch (relay_range) {
	case 0:
		range_control = 0x0f;
		break;
	case 1:
		range_control = 0x07;
		break;
	case 2:
		range_control = 0x03;
		break;
	case 3:
		range_control = 0x01;
		break;
	case 4:
	default:
		range_control = 0x00;
		break;
	}

	I2C_Write(PCF8574,range_control);

	globals.ChannelState[channel].slew = new_slew;

	Set_Update_Chans();

	return OK;
}


int Set_avrq_ampl(int check_possible_only,int word_override,int range_override,int channel,float new_avrq_ampl)
{
	int check_valid;
	int status,point_found,relay_range,UseNegData,entry,actual_pol,word_out,dummy;
	int true_channel;
	int use_pwl;

	if (!globals.Flash.enable_avrq_extra_ampls) {
		return Unrecognized;
	}

	/* check channels */
	if ((channel < 1) || (channel>4)) {
		return InvalidChannel;
	}

	if (channel == 1) {
		true_channel = 1;
	} else {
		true_channel = 0;
	}

	if (!check_possible_only) {
		/* check duty cycle */
		int i;
		for (i=0; i<max_channels; ++i) {
			TestState[i]=globals.ChannelState[i];
		}
		switch (channel) {
		case 1:
			TestState[true_channel].amplitude=new_avrq_ampl;
			break;
		case 2:
			TestState[true_channel].vcc1=new_avrq_ampl;
			if (TestState[true_channel].vlogic >= smallest_allowed_number) {
				TestState[true_channel].vlogic = new_avrq_ampl;
			}
			break;
		case 3:
			TestState[true_channel].vcc2=new_avrq_ampl;
			break;
		case 4:
			TestState[true_channel].vlogic=new_avrq_ampl;
			break;
		}
		if ((check_valid=Error_check(TestState))) {
			return check_valid;
		}
	}

	/* find appropriate range/fine settings from piece-wise linear data in flash memory */
	if (word_override) {
		word_out=word_override;
		relay_range=range_override;
	} else {
		switch (channel) {
		case 1:
			use_pwl = pwl_ampl_values;
			break;
		case 2:
			use_pwl = pwl_vcc1_values;
			break;
		case 3:
			use_pwl = pwl_vcc2_values;
			break;
		case 4:
			use_pwl = pwl_vlogic_values;
			if (new_avrq_ampl > 0.0) {
				new_avrq_ampl = globals.ChannelState[true_channel].vcc1;
			}
			break;
		}

		if (use_pwl != pwl_vlogic_values)
			if ((status=Set_VI_Control(use_pwl,channel,new_avrq_ampl,&point_found,&relay_range,&dummy,&UseNegData,&entry,&word_out,&actual_pol))) {
				return status;
			}

	}

	if (check_possible_only) {
		if (point_found) {
			return OK;
		} else {
			return CalibrationMinMaxError;
		}
	}


	/* update variables if OK */
	switch (channel) {
	case 1:
		Set_avrq_ampl(0,0,0,4,0.0);

		set_dac(1,word_out);

		globals.Registers.avrq_reg = globals.Registers.avrq_reg & 0x3f;
		I2C_Write(PCF8574A+rise_time_port,globals.Registers.avrq_reg);

		if (new_avrq_ampl!=globals.ChannelState[true_channel].amplitude) {
			globals.Changes.update_amp=YES;
		}
		globals.ChannelState[true_channel].amplitude=new_avrq_ampl;
		break;
	case 2:
		set_dac(1,word_out);

		globals.Registers.avrq_reg = 0x40 | (globals.Registers.avrq_reg & 0xbf);
		I2C_Write(PCF8574A+rise_time_port,globals.Registers.avrq_reg);

		if (new_avrq_ampl!=globals.ChannelState[true_channel].vcc1) {
			globals.Changes.update_amp=YES;
		}
		globals.ChannelState[true_channel].vcc1=new_avrq_ampl;
		break;
	case 3:
		set_dac(0,word_out);
		if (new_avrq_ampl!=globals.ChannelState[true_channel].vcc2) {
			globals.Changes.update_amp=YES;
		}
		globals.ChannelState[true_channel].vcc2=new_avrq_ampl;

		/* update ampl-dependent load resistance */
		Set_avrq_res(0,0,0,0,globals.ChannelState[0].load_type);

		break;
	case 4:
		if (new_avrq_ampl >= smallest_allowed_number) {
			relay_range = 0x80;
		} else {
			relay_range = 0x0;
		}
		globals.Registers.avrq_reg = relay_range | (globals.Registers.avrq_reg & 0x7f);
		I2C_Write(PCF8574A+rise_time_port,globals.Registers.avrq_reg);

		if (new_avrq_ampl!=globals.ChannelState[true_channel].vlogic) {
			globals.Changes.update_amp=YES;
		}
		globals.ChannelState[true_channel].vlogic=new_avrq_ampl;
		break;
	}


	/* reduce vlogic based on vcc1, if required */
	if (channel == 2) {
		if (globals.ChannelState[true_channel].vlogic > smallest_allowed_number) {
			Set_avrq_ampl(0,0,0,4,globals.ChannelState[true_channel].vcc1);
		} else {
			Set_avrq_ampl(0,0,0,4,0.0);
		}
	}

	/* reduce vcc1 if ibias is active, because they share a DAC */
	if ((channel == 1) && (globals.ChannelState[true_channel].amplitude > smallest_allowed_number)) {
		globals.ChannelState[0].vcc1=0.0;
	}

	/* reduce vcc1 if ibias is active, because they share a DAC */
	if ((channel == 2) && (globals.ChannelState[true_channel].vcc1 > smallest_allowed_number)) {
		globals.ChannelState[1].amplitude=0.0;
	}

	Set_Update_Chans();

	return OK;
}


int go_cal(CalStruct *caldata)
{
	int i, status, points;
	float meas, nom_val, change;
	float min_val, max_val, chk_val;

	gchar *lcd_msg = NULL;
	gchar *prefix = NULL;

	points = Get_VI_Num_Pnts(caldata->cal_type,caldata->channel);

	caldata->count = 0;
	caldata->error = 0;
	caldata->max_change = 0.0;
	caldata->avg_change = 0.0;

	min_val = 100e-6;
	if (caldata->cal_type == pwl_period_values) {
		max_val = 4.0 / globals.Flash.min_freq[caldata->channel];
		chk_val = 0.25 / globals.Flash.max_freq[caldata->channel];
		if (chk_val > min_val) {
			min_val = chk_val;
		}
	} else if (caldata->cal_type == pwl_pw_values) {
		max_val = 4.0 * globals.Flash.max_pw[caldata->channel];
		chk_val = 0.25 * globals.Flash.min_pw[caldata->channel];
		if (chk_val > min_val) {
			min_val = chk_val;
		}
	} else if (caldata->cal_type == pwl_delay_values) {
		max_val = 4.0 * globals.Flash.max_delay[caldata->channel];
	}

	for (i=1; i<=points; i++) {
		Set_Cal_Nom(caldata->channel,i,caldata->cal_type,&nom_val);
		if ( (nom_val >= min_val) && (nom_val <= max_val) ) {
			Set_Cal_Nom(caldata->channel,i,caldata->cal_type,NULL);

			LCD_clear();
			LCD_write(0,0,"Self-calibration in progress.");

			if (caldata->cal_type == pwl_period_values) {
				prefix = g_strdup_printf ("CH%d PER %d:",caldata->channel+1,i);
			} else if (caldata->cal_type == pwl_pw_values) {
				prefix = g_strdup_printf ("CH%d PW %d:",caldata->channel+1,i);
			} else if (caldata->cal_type == pwl_delay_values) {
				prefix = g_strdup_printf ("CH%d DLY %d:",caldata->channel+1,i);
			}

			lcd_msg = g_strdup_printf ("%s %.3e",prefix,nom_val);
			LCD_write(2,0,lcd_msg);
			g_free (lcd_msg);

			if (caldata->cal_type == pwl_period_values) {
				I2C_Self_Cal (caldata->channel, MEAS_PRF, &meas, 1.0 / globals.ChannelState[caldata->channel].frequency);
			} else if (caldata->cal_type == pwl_pw_values) {
				I2C_Self_Cal (caldata->channel, MEAS_PW, &meas, globals.ChannelState[caldata->channel].pw);
			} else {
				I2C_Self_Cal (caldata->channel, MEAS_PW, &meas, globals.ChannelState[caldata->channel].delay);
			}

			change = 100.0 * (meas-nom_val)/nom_val;
			status = Set_VI_Cal_Pnt(caldata->cal_type,caldata->channel,i,meas);
			if (status) {
				++caldata->error;
			} else {
				++caldata->count;
				if (fabs(change)>caldata->max_change) {
					caldata->max_change = change;
				}
				caldata->avg_change = ((caldata->avg_change * (((float) caldata->count) - 1.0)) + change) / caldata->count;
			}

			LCD_clear();
			LCD_write(0,0,"Self-calibration in progress.");

			lcd_msg = g_strdup_printf ("%s %.3e -> %.3e",prefix,nom_val,meas);
			LCD_write(2,0,lcd_msg);
			g_free (lcd_msg);

			lcd_msg = g_strdup_printf ("changed %6.2f%%, err: %d",change,status);
			LCD_write(3,0,lcd_msg);
			g_free (lcd_msg);

			g_free (prefix);

			g_usleep (2e6);
		}
	}

	return OK;
}


void cal_string(char *parameter, CalStruct *caldata)
{
	gchar *string = g_strdup_printf ("CH%d %s cal: %d errors. Adj: %6.2f%% max, %6.2f%% avg.\r\n", caldata->channel+1,parameter, caldata->error, caldata->max_change, caldata->avg_change);
	g_string_append (caldata->response, string);
	g_free (string);
}


int self_cal()
{
	CalStruct caldata;

	int status = do_full_self_cal(&caldata);

	g_string_free (caldata.response, TRUE);

	return status;
}


int do_full_self_cal(CalStruct *caldata)
{
	gchar *string;
	long start_timer, diff_timer;
	int eprom_loc;

	caldata->response = g_string_new ("");

	Menu_Clear_Buttons();
	LCD_clear();              /*0123456789012345678901234567890123456789*/
	LCD_write(0,0,"Self-calibration in progress.");
	/*0123456789012345678901234567890123456789*/

	string = g_strdup_printf ("Typical run time: %d min, %d sec.", globals.Flash.self_cal_typical_time_min, globals.Flash.self_cal_typical_time_sec);
	LCD_write(1,0,string);
	g_free (string);

	while ((sec_timer() - globals.Timers.startup_timer_value) < (long)globals.Flash.self_cal_pause) {
		/*0123456789012345678901234567890123456789*/
		string = g_strdup_printf ("Min warm-up is %ds, on for %lds.", globals.Flash.self_cal_pause, sec_timer() - globals.Timers.startup_timer_value);
		LCD_write(3,0,string);
		g_free (string);
		g_usleep (2e5);
	}

	start_timer = sec_timer();
	caldata->total_errors = 0;
	caldata->total_max_change = 0.0;

	caldata->cal_type = pwl_pw_values;
	for (caldata->channel=0; caldata->channel<(globals.Flash.ChanKey_pw?globals.Flash.channels:1); ++caldata->channel) {
		go_cal(caldata);
		cal_string("PW", caldata);
		caldata->total_errors += caldata->error;
		if (fabs(caldata->total_max_change) < fabs(caldata->max_change)) {
			caldata->total_max_change = caldata->max_change;
		}
	}

	caldata->cal_type = pwl_delay_values;
	for (caldata->channel=0; caldata->channel<(globals.Flash.ChanKey_delay?globals.Flash.channels:1); ++caldata->channel) {
		go_cal(caldata);
		cal_string("Delay", caldata);
		caldata->total_errors += caldata->error;
		if (fabs(caldata->total_max_change) < fabs(caldata->max_change)) {
			caldata->total_max_change = caldata->max_change;
		}
	}

	caldata->cal_type = pwl_period_values;
	for (caldata->channel=0; caldata->channel<(globals.Flash.ChanKey_frequency?globals.Flash.channels:1); ++caldata->channel) {
		go_cal(caldata);
		cal_string("Period", caldata);
		caldata->total_errors += caldata->error;
		if (fabs(caldata->total_max_change) < fabs(caldata->max_change)) {
			caldata->total_max_change = caldata->max_change;
		}
	}

	Main_Rst();

	LCD_clear();              /*0123456789012345678901234567890123456789*/
	LCD_write(0,0,"Self-calibration complete.");

	string = g_strdup_printf ("%d errors. Max change: %6.2f%%", caldata->total_errors, caldata->total_max_change);
	LCD_write(1,0,string);
	g_free (string);

	LCD_write(2,0,"More details are provided by \"cal?\"");
	g_usleep (3e6);

	Show_Main_Menu();

	diff_timer = sec_timer() - start_timer;

	globals.Flash.self_cal_typical_time_min = (int) (diff_timer / 60);
	globals.Flash.self_cal_typical_time_sec = (int) (diff_timer % 60);

	string = g_strdup_printf ("Completed in %d minutes and %d seconds\r\n", globals.Flash.self_cal_typical_time_min, globals.Flash.self_cal_typical_time_sec);
	g_string_append (caldata->response, string);
	g_free (string);

	eprom_loc = (char *) &(globals.Flash.self_cal_typical_time_min) - (char *) &(globals.Flash.flash_start);
	writeUserBlock(&globals.Flash, eprom_loc, sizeof(globals.Flash.self_cal_typical_time_min));
	eprom_loc = (char *) &(globals.Flash.self_cal_typical_time_sec) - (char *) &(globals.Flash.flash_start);
	writeUserBlock(&globals.Flash, eprom_loc, sizeof(globals.Flash.self_cal_typical_time_sec));

	if (caldata->total_errors) {
		return SelfCalError;
	} else {
		return OK;
	}
}


int I2C_Self_Cal(int channel, int meas_mode, float *meas, float target_time)
{
#define MAX_TRIES 35
#define AVG_TRIES 4

	int word, buffer, ch_mode;
	long count;
	float measuring_time;
	float min_time;
	float avg, max_error, this, this_error;
	int iter, stable,i;
	float prev[AVG_TRIES];

	for (i=0; i<AVG_TRIES; i++) {
		prev[i]=0.0;
	}

	*meas = 0.0;
	stable = 0;

	if (channel) {
		ch_mode = MEAS_CH2;
	} else {
		ch_mode = MEAS_CH1;
	}

	measuring_time = 1.0;

	min_time = globals.ChannelState[channel].pw * 3.0;
	if (min_time > measuring_time) {
		measuring_time = min_time;
	}

	min_time = (1.0/globals.ChannelState[channel].frequency);
	if (min_time > measuring_time) {
		measuring_time = min_time;
	}

	if (meas_mode == MEAS_PRF) {
		min_time = (1.0/globals.ChannelState[channel].frequency) * 3.0;
		if (min_time > measuring_time) {
			measuring_time = min_time;
		}
	}

	min_time = fabs(globals.ChannelState[channel].delay) * 3.0;
	if (min_time > measuring_time) {
		measuring_time = min_time;
	}

	for (iter = 1; (iter <= MAX_TRIES) && !stable; iter++) {

		if (iter <= LCD_cols) {
			LCD_write(3,(iter-1) % 35,". ");
		}

		if (meas_mode == MEAS_PW) {
			start_gate_override ();
			// delay to let oscillator reset, within 20% of a period?
			g_usleep((gulong) (2.0e5 / globals.ChannelState[channel].frequency));
		}

		// reset counters
		word = NOT_ENABLE_COUNT | NOT_LOAD_BUFFERS_CLK | CLR_COUNTERS | meas_mode | ch_mode | COUNTER_BYTE_0;
		I2C_Write(PCF8574+To_Self_Cal_Port,word);
		word = NOT_ENABLE_COUNT | NOT_LOAD_BUFFERS_CLK | NOT_CLR_COUNTERS | meas_mode | ch_mode | COUNTER_BYTE_0;
		I2C_Write(PCF8574+To_Self_Cal_Port,word);

		// arm flip-flops
		word = ENABLE_COUNT | NOT_LOAD_BUFFERS_CLK | NOT_CLR_COUNTERS | meas_mode | ch_mode | COUNTER_BYTE_0;
		I2C_Write(PCF8574+To_Self_Cal_Port,word);
		word = NOT_ENABLE_COUNT | NOT_LOAD_BUFFERS_CLK | NOT_CLR_COUNTERS | meas_mode | ch_mode | COUNTER_BYTE_0;
		I2C_Write(PCF8574+To_Self_Cal_Port,word);

		if (meas_mode == MEAS_PW) {
			stop_gate_override ();
		}

		// time to measure
		g_usleep((gulong) (measuring_time * 1.0e6));

		// latch into buffers
		word = NOT_ENABLE_COUNT | LOAD_BUFFERS_CLK | NOT_CLR_COUNTERS | meas_mode | ch_mode | COUNTER_BYTE_0;
		I2C_Write(PCF8574+To_Self_Cal_Port,word);
		word = NOT_ENABLE_COUNT | NOT_LOAD_BUFFERS_CLK | NOT_CLR_COUNTERS | meas_mode | ch_mode | COUNTER_BYTE_0;
		I2C_Write(PCF8574+To_Self_Cal_Port,word);

		// read buffers
		buffer = I2C_Read (PCF8574+From_Self_Cal_Port);
		count = (long) buffer;

		word = NOT_ENABLE_COUNT | NOT_LOAD_BUFFERS_CLK | NOT_CLR_COUNTERS | meas_mode | ch_mode | COUNTER_BYTE_1;
		I2C_Write(PCF8574+To_Self_Cal_Port,word);
		buffer = I2C_Read (PCF8574+From_Self_Cal_Port);
		count = count | ((long) buffer << 8);

		word = NOT_ENABLE_COUNT | NOT_LOAD_BUFFERS_CLK | NOT_CLR_COUNTERS | meas_mode | ch_mode | COUNTER_BYTE_2;
		I2C_Write(PCF8574+To_Self_Cal_Port,word);
		buffer = I2C_Read (PCF8574+From_Self_Cal_Port);
		count = count | ((long) buffer << 16);

		word = NOT_ENABLE_COUNT | NOT_LOAD_BUFFERS_CLK | NOT_CLR_COUNTERS | meas_mode | ch_mode | COUNTER_BYTE_3;
		I2C_Write(PCF8574+To_Self_Cal_Port,word);
		buffer = I2C_Read (PCF8574+From_Self_Cal_Port);
		count = count | ((long) buffer << 24);

		if (count < 100) {
			//return SelfCalError;
			if (iter <= LCD_cols) {
				LCD_write(3,iter-1,"x");
			}
			continue;
		}

		this = count * 100e-9;
		max_error = 0.001;
		avg = 0.0;

		for (i=0; i<(AVG_TRIES-1); i++) {
			prev[i]=prev[i+1];
		}
		prev[AVG_TRIES-1] = this;
		for (i = 0; i<AVG_TRIES; i++) {
			avg += (prev[i]/AVG_TRIES);
		}

		this_error = fabs ((this - avg) / avg);
		if (this_error < max_error) {
			stable = 1;
		}
	}

	if (!stable) {
		return SelfCalError;
	}

	*meas = this;
	return OK;
}


void Set_Rcl(int setting_num)
{
	int temp;
	int i;

	globals.Flags.do_check_settings=NO;	/* don't check for conflicting settings */
	globals.Flags.extended_ampl_min_max=NO;

	// go backwards, so channel 0 overrides everything
	for (i=globals.Flash.channels-1; i>=0; --i) {

		globals.ChannelState[i].route_primary=globals.Flash.rcl_route_primary[i][setting_num];
		globals.ChannelState[i].route_secondary=globals.Flash.rcl_route_secondary[i][setting_num];

		globals.ChannelState[i].frequency=globals.Flash.rcl_frequency[i][setting_num];
		globals.ChannelState[i].delay=globals.Flash.rcl_delay[i][setting_num];
		globals.ChannelState[i].pw=globals.Flash.rcl_pw[i][setting_num];
		globals.ChannelState[i].amplitude=globals.Flash.rcl_amplitude[i][setting_num];
		globals.ChannelState[i].offset=globals.Flash.rcl_offset[i][setting_num];
		globals.ChannelState[i].burst_count=globals.Flash.rcl_burst_count[i][setting_num];
		globals.ChannelState[i].burst_time=globals.Flash.rcl_burst_time[i][setting_num];
		globals.ChannelState[i].rise_time=globals.Flash.rcl_rise_time[i][setting_num];
		globals.ChannelState[i].slew=globals.Flash.rcl_slew[i][setting_num];

		globals.ChannelState[i].vcc1=globals.Flash.rcl_vcc1[i][setting_num];
		globals.ChannelState[i].vcc2=globals.Flash.rcl_vcc2[i][setting_num];
		globals.ChannelState[i].vlogic=globals.Flash.rcl_vlogic[i][setting_num];

		globals.ChannelState[i].soft_current_limit=globals.Flash.rcl_soft_current_limit[i][setting_num];
		globals.ChannelState[i].load_type=globals.Flash.rcl_load[i][setting_num];

		temp=globals.Flash.rcl_misc[i][setting_num];

		if (temp&1) {
			globals.ChannelState[i].zout=globals.Flash.zout_max[i];
		} else {
			globals.ChannelState[i].zout=globals.Flash.zout_min[i];
		}
		globals.ChannelState[i].hold_setting = (temp >> 1) & 1;
		globals.ChannelState[i].double_pulse = (temp >> 2) & 1;
		globals.ChannelState[i].pw_ctrl_mode = (temp >> 3) & 3;
		globals.ChannelState[i].polarity = (temp >> 5) & 1;
		globals.ChannelState[i].output_state = (temp >> 6) & 1;
		globals.ChannelState[i].gate_type = (temp >> 7) & 1;
		globals.ChannelState[i].trigger_source = (temp >> 8) & 7;
		globals.ChannelState[i].amp_mode = (temp >> 11) & 1;
		globals.ChannelState[i].gate_level = (temp >> 12) & 1;
		globals.ChannelState[i].logic_level = (temp >> 14) & 1;
		globals.ChannelState[i].os_mode = (temp >> 15) & 1;

		temp=globals.Flash.rcl_misc2[i][setting_num];
		/* the high bit of amp_mode was added later; hence the odd reconstruction */
		globals.ChannelState[i].amp_mode |= (temp << 1) & 2;
		globals.ChannelState[i].func_mode = (temp >> 2) & 0x1f;	/* 5 bits! */

		Set_Route(i,ROUTE_PRIMARY,globals.ChannelState[i].route_primary);
		Set_Route(i,ROUTE_SECONDARY,globals.ChannelState[i].route_secondary);

		Set_frequency(0,0,0,i,globals.ChannelState[i].frequency);
		Set_Delay(0,0,0,i,globals.ChannelState[i].delay);

		Set_Pw(0,0,0,i,globals.ChannelState[i].pw,0);

		Set_Double(i,globals.ChannelState[i].double_pulse);
		Set_Pwmode(i,globals.ChannelState[i].pw_ctrl_mode);

		Set_Func(i,globals.ChannelState[i].func_mode);
		Set_Pol(i,globals.ChannelState[i].polarity);
		Set_Gate_Sync(i,globals.ChannelState[i].gate_type);
		Set_Gate_Level(i,globals.ChannelState[i].gate_level);
		Set_EA(i,globals.ChannelState[i].amp_mode);
		Set_EO(i,globals.ChannelState[i].os_mode);

		if (globals.Flash.switchable_zout[i]) {
			Set_zout(i,globals.ChannelState[i].zout,1);
		}

		Set_Load(i,globals.ChannelState[i].load_type);
		Set_Logic_Level(i,globals.ChannelState[i].logic_level);
		Set_rise_time(0,0,0,i,globals.ChannelState[i].rise_time);
		Set_slew(0,0,0,i,globals.ChannelState[i].slew);
		Set_current_limit(0,i,globals.ChannelState[i].soft_current_limit);

		if (globals.Flash.max_burst_count[i]>1) {
			Set_Burst_Count(i,globals.ChannelState[i].burst_count,globals.ChannelState[i].burst_time);
		}

		Set_Trig_Source(i,globals.ChannelState[i].trigger_source);

		Set_Amplitude(0,0,0,0,0,0,i,globals.ChannelState[i].amplitude,0);

		if	 (globals.Flash.voltage_offset_enabled[i] || globals.Flash.current_offset_enabled[i]) {
			Set_Offset(0,0,0,0,i,globals.ChannelState[i].offset);
		}

		Set_avrq_ampl(0,0,0,2,globals.ChannelState[i].vcc1);
		Set_avrq_ampl(0,0,0,3,globals.ChannelState[i].vcc2);
		Set_avrq_ampl(0,0,0,4,globals.ChannelState[i].vlogic);

		Set_Output_State(i,globals.ChannelState[i].output_state);

	}

	Menu_Clear_Buttons();

	globals.Flags.do_check_settings=YES;	/* check for conflicting settings */

	Error_check(globals.ChannelState);	/* establishes min/max values for queries, but reports no errors */

	return;
}


void Set_Sav(int setting_num)
{
	int temp;
	int i;

	for (i=0; i<globals.Flash.channels; i++) {

		/* float and large integers */
		globals.Flash.rcl_route_primary[i][setting_num]=globals.ChannelState[i].route_primary;
		globals.Flash.rcl_route_secondary[i][setting_num]=globals.ChannelState[i].route_secondary;

		globals.Flash.rcl_frequency[i][setting_num]=globals.ChannelState[i].frequency;
		globals.Flash.rcl_delay[i][setting_num]=globals.ChannelState[i].delay;
		globals.Flash.rcl_pw[i][setting_num]=globals.ChannelState[i].pw;
		globals.Flash.rcl_amplitude[i][setting_num]=globals.ChannelState[i].amplitude;
		globals.Flash.rcl_offset[i][setting_num]=globals.ChannelState[i].offset;
		globals.Flash.rcl_burst_count[i][setting_num]=globals.ChannelState[i].burst_count;
		globals.Flash.rcl_burst_time[i][setting_num]=globals.ChannelState[i].burst_time;
		globals.Flash.rcl_rise_time[i][setting_num]=globals.ChannelState[i].rise_time;
		globals.Flash.rcl_slew[i][setting_num]=globals.ChannelState[i].slew;
		globals.Flash.rcl_soft_current_limit[i][setting_num]=globals.ChannelState[i].soft_current_limit;
		globals.Flash.rcl_load[i][setting_num]=globals.ChannelState[i].load_type;
		globals.Flash.rcl_vcc1[i][setting_num]=globals.ChannelState[i].vcc1;
		globals.Flash.rcl_vcc2[i][setting_num]=globals.ChannelState[i].vcc2;
		globals.Flash.rcl_vlogic[i][setting_num]=globals.ChannelState[i].vlogic;

		/* integers	 		setting_nums
		globals.ChannelState[i].zout					50 (1) or min (0)
		globals.ChannelState[i].hold_setting		hold_width 0, hold_duty 1
		globals.ChannelState[i].double_pulse		double_on 1, double_off 0
		globals.ChannelState[i].pw_ctrl_mode				pw_normal 1, pw_in_out 0
		globals.ChannelState[i].func_mode			pulse_mode_on 0, dc_mode_on 1
		globals.ChannelState[i].polarity				pol_norm 0, pol_complement 1
		globals.ChannelState[i].output_state		output_off 0,output_on 1
		globals.ChannelState[i].gate_type			gate_sync 0, gate_async 1
		globals.ChannelState[i].trigger_source		source_internal 0, source_external 1, source_manual 2, source_hold 3, source_immediate 4
		globals.ChannelState[i].amp_mode			normal 0, ea 1, ext amplify 2
		globals.ChannelState[i].gate_level			gate_low 0, gate_high 1
		*/

		/* compress the assorted integer parameters into a single bitmapped integer */
		if (globals.ChannelState[i].zout==globals.Flash.zout_max[i]) {
			temp=1;
		} else {
			temp=0;
		}
		temp |= globals.ChannelState[i].hold_setting << 1;
		temp |= globals.ChannelState[i].double_pulse << 2;
		temp |= globals.ChannelState[i].pw_ctrl_mode << 3;
		temp |= globals.ChannelState[i].polarity << 5;
		temp |= globals.ChannelState[i].output_state << 6;
		temp |= globals.ChannelState[i].gate_type << 7;
		temp |= globals.ChannelState[i].trigger_source << 8;
		temp |= (globals.ChannelState[i].amp_mode & 1) << 11;
		temp |= globals.ChannelState[i].gate_level << 12;
		temp |= globals.ChannelState[i].logic_level << 14;
		temp |= globals.ChannelState[i].os_mode << 15;

		globals.Flash.rcl_misc[i][setting_num]=temp;

		/* need another integer to hold everything now */
		temp  = 0;
		temp |= ( (globals.ChannelState[i].amp_mode>1) & 1) << 0;
		temp |= globals.ChannelState[i].func_mode << 2;	/* 5 bits! */

		globals.Flash.rcl_misc2[i][setting_num]=temp;

	}

	/* save everything */
	writeUserBlock(&globals.Flash, 0, sizeof(globals.Flash));

	return;
}


void Main_update_shift_registers()
{
	static GStaticMutex mutex = G_STATIC_MUTEX_INIT;
	g_static_mutex_lock (&mutex);

	/* send MSB first, LSB last */
	/* send highest # SR first */

	int i,j,n;	  /* counters */
	char data_out;
	int temp_output_state[max_channels];

	/* suppress triggering during relay switching */
	if (	globals.Registers.last_relay_driver_settings[0]!=globals.Registers.shift_reg_out[2]
	                || globals.Registers.last_relay_driver_settings[1]!=globals.Registers.shift_reg_out[3]) {
		start_gate_override ();
	}


	/* physically turn off output for amplitude range changes */
	/* i.e., short output in 155's */
	if (globals.Flags.force_output_fully_off==YES)
		for (i=0; i<(globals.Flash.ChanKey_frequency?globals.Flash.channels:1); ++i) {
			temp_output_state[i]=globals.ChannelState[i].output_state;
			Set_Output_State(i,output_off);
			g_usleep (1e3 * globals.Timers.normal_relay_bounce_time_in_milliseconds);
		}

	bus_setpin(out_CLOCK_LINE, 1);
	bus_setpin(out_STROBE_LINE, 0);

	for (i=(num_out_SRs-1); i>=0; --i) {
		switch (i) {
		case 0:
		case 1:
			n=8;
			break;
		case 2:
		case 3:
			n=20;			/* 20 bit shift registers - UCN5812s */
			break;
		}

		for (j=n-1; j>=0; --j) {	/* send MSB first, LSB last */
			bus_setpin(out_CLOCK_LINE, 0);
			data_out = (char) (1 & (globals.Registers.shift_reg_out[i]>>j));
			bus_setpin(out_DATA_LINE, data_out);
			bus_setpin(out_CLOCK_LINE, 1);
		}
	}

	bus_setpin(out_STROBE_LINE, 1);		// latch the data
	bus_setpin(out_STROBE_LINE, 0);		// release latch

	for (i=0; i<8; ++i) {
		/* load the upper-nibble latch */
		bus_writebyte ((uint8_t) (Octal_DACportCS_high), (uint8_t) (globals.Registers.parallel_DAC_reg[i]  >> 8));

		/* write lower byte (with address data), and force transfer of latched nibble */
		bus_writebyte ((uint8_t) (Octal_DACportCS_low + i), (uint8_t) (globals.Registers.parallel_DAC_reg[i] & 255));
	}

	/* keep trigger suppressed for a time (normally 5ms) after a relay update */
	if (	globals.Registers.last_relay_driver_settings[0]!=globals.Registers.shift_reg_out[2]
	                || globals.Registers.last_relay_driver_settings[1]!=globals.Registers.shift_reg_out[3]
	                || globals.Flags.force_output_fully_off==YES) {
		g_usleep (1e3 * globals.Timers.Relay_Switching_Delay_in_Milliseconds);
	}


	/* restore output if required */
	if (globals.Flags.force_output_fully_off==YES)
		for (i=0; i<(globals.Flash.ChanKey_frequency?globals.Flash.channels:1); ++i) {
			Set_Output_State(i,temp_output_state[i]);
			g_usleep (1e3 * globals.Timers.normal_relay_bounce_time_in_milliseconds);
			globals.Flags.force_output_fully_off=NO;
		}

	stop_gate_override ();

	globals.Timers.Relay_Switching_Delay_in_Milliseconds=globals.Timers.normal_relay_bounce_time_in_milliseconds;
	/* restore default delay */

	/* save relay data for comparision next time */
	globals.Registers.last_relay_driver_settings[0]=globals.Registers.shift_reg_out[2];
	globals.Registers.last_relay_driver_settings[1]=globals.Registers.shift_reg_out[3];

	// reset update sensors
	globals.Changes.update_os = 0;
	globals.Changes.update_amp = 0;
	globals.Changes.update_zout = 0;
	globals.Changes.update_load = 0;

	g_static_mutex_unlock (&mutex);
}


int IO_Setup_RS232(int baud, char hardhand, gboolean update_flash)
{
	FILE* configfile = fopen("/tmp/instgettyopts", "w");
	if(configfile) {
		fprintf(configfile, "OPTS=-L %s\n", hardhand ? "-h" : "");
		fprintf(configfile, "BAUD=%d\n", baud);
		fclose(configfile);
		system("systemctl --no-block restart inst-getty@ttyO5.service");
	}

	globals.Flash.baud = baud;
	globals.Flash.hardhand = hardhand;

	if (update_flash) {
		int size = sizeof(globals.Flash.baud) + sizeof(globals.Flash.parity) + sizeof(globals.Flash.stopbits) +
		           sizeof(globals.Flash.databits) + sizeof(globals.Flash.hardhand) + sizeof(globals.Flash.echo);

		int eprom_loc = (char *) &(globals.Flash.baud) - (char *) &(globals.Flash.flash_start);
		writeUserBlock(&globals.Flash, eprom_loc, size);
	}
	return OK;
}

// this is a conversation handler for pam, it basically sends the password when pam asks for it

static int conversation(int num_msg, const struct pam_message **msgs, struct pam_response **resp, void *appdata_ptr)
{

	struct pam_response* responses = calloc(num_msg, sizeof(struct pam_response));
	if (!responses) {
		return PAM_CONV_ERR;
	}

	int i; // not compiling in gnu99 mode?
	for (i = 0; i < num_msg; i++) {
		const struct pam_message *msg = msgs[i];
		struct pam_response* response = &(responses[i]);
		switch (msg->msg_style) {
		case PAM_PROMPT_ECHO_OFF:
			response->resp = strdup((char*) appdata_ptr);
			if (!response->resp) {
				return PAM_CONV_ERR;
			}
			break;

		default:
			return PAM_CONV_ERR;
		}
		response->resp_retcode = 0;
	}

	*resp = responses;

	return PAM_SUCCESS;
}

static gboolean checkpassword(const char* username, char* password)
{
	struct pam_conv pam_conversation = { conversation, password };
	pam_handle_t* pamh;

	if (pam_start("passwd", username, &pam_conversation, &pamh) != PAM_SUCCESS) {
		return FALSE;
	}

	if (pam_authenticate(pamh, 0) != PAM_SUCCESS) {
		return FALSE;
	}

	// we only want to check the password and not actually start a session, so get out of here

	pam_end(pamh, 0);

	return TRUE;
}

int change_password(gchar *old_password, gchar *new_password)
{

	gboolean old_valid = TRUE;

	char* user = "admin";

	// Skip password check if the supplied old_password is NULL. This
	// only happens when resetting the password to the default.
	if (old_password != NULL ) {
		old_valid = checkpassword(user,old_password);
	}

	if (old_valid == TRUE) {
		struct lu_context *ctx;
		struct lu_error *error = NULL;
		struct lu_ent *ent;

		ctx = lu_start(user, lu_user, NULL, NULL, lu_prompt_console_quiet, NULL, &error);

		if (ctx == NULL ) {
			return password_change_error;
		}

		ent = lu_ent_new();

		if (lu_user_lookup_name(ctx, user, ent, &error) == FALSE) {
			return password_change_error; // user doesn't exist
		}

		if (lu_user_setpass(ctx, ent, new_password, FALSE, &error) == FALSE) {
			return password_change_error;
		}

		lu_end(ctx);

		return OK;
	} else {
		return password_change_error;
	}
}


static void set_shiftreg_bits(int shiftreg, int start_at_bit, int numbits, int value)
{
	long used_bits = (1<<numbits) - 1;
	long mask = 0xfffff - (used_bits << start_at_bit);

	long shift_value = (value & used_bits) << start_at_bit;
	long masked_reg = globals.Registers.shift_reg_out[shiftreg] & mask;

//        printf ("shiftreg %d, start_at_bit %d, numbits %d, value %x\n",shiftreg,start_at_bit,numbits,value);
//        printf (" in %lx\n", globals.Registers.shift_reg_out[shiftreg]);
	globals.Registers.shift_reg_out[shiftreg] = masked_reg | shift_value;
//        printf ("out %lx\n", globals.Registers.shift_reg_out[shiftreg]);
}