File: Configuration.cpp

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

//
// Read me!
//
// This file defines a configuration dialog with the user. The general
// strategy is to expose agreed  configuration parameters via a custom
// interface (See  Configuration.hpp). The state exposed  through this
// public   interface  reflects   stored  or   derived  data   in  the
// Configuration::impl object.   The Configuration::impl  structure is
// an implementation of the PIMPL (a.k.a.  Cheshire Cat or compilation
// firewall) implementation hiding idiom that allows internal state to
// be completely removed from the public interface.
//
// There  is a  secondary level  of parameter  storage which  reflects
// current settings UI  state, these parameters are not  copied to the
// state   store  that   the  public   interface  exposes   until  the
// Configuration:impl::accept() operation is  successful. The accept()
// operation is  tied to the settings  OK button. The normal  and most
// convenient place to store this intermediate settings UI state is in
// the data models of the UI  controls, if that is not convenient then
// separate member variables  must be used to store that  state. It is
// important for the user experience that no publicly visible settings
// are changed  while the  settings UI are  changed i.e.  all settings
// changes   must    be   deferred   until   the    "OK"   button   is
// clicked. Conversely, all changes must  be discarded if the settings
// UI "Cancel" button is clicked.
//
// There is  a complication related  to the radio interface  since the
// this module offers  the facility to test the  radio interface. This
// test means  that the  public visibility to  the radio  being tested
// must be  changed.  To  maintain the  illusion of  deferring changes
// until they  are accepted, the  original radio related  settings are
// stored upon showing  the UI and restored if the  UI is dismissed by
// canceling.
//
// It  should be  noted that  the  settings UI  lives as  long as  the
// application client that uses it does. It is simply shown and hidden
// as it  is needed rather than  creating it on demand.  This strategy
// saves a  lot of  expensive UI  drawing at the  expense of  a little
// storage and  gives a  convenient place  to deliver  settings values
// from.
//
// Here is an overview of the high level flow of this module:
//
// 1)  On  construction the  initial  environment  is initialized  and
// initial   values  for   settings  are   read  from   the  QSettings
// database. At  this point  default values for  any new  settings are
// established by  providing a  default value  to the  QSettings value
// queries. This should be the only place where a hard coded value for
// a   settings  item   is   defined.   Any   remaining  one-time   UI
// initialization is also done. At the end of the constructor a method
// initialize_models()  is called  to  load the  UI  with the  current
// settings values.
//
// 2) When the settings UI is displayed by a client calling the exec()
// operation, only temporary state need be stored as the UI state will
// already mirror the publicly visible settings state.
//
// 3) As  the user makes  changes to  the settings UI  only validation
// need be  carried out since the  UI control data models  are used as
// the temporary store of unconfirmed settings.  As some settings will
// depend  on each  other a  validate() operation  is available,  this
// operation implements a check of any complex multi-field values.
//
// 4) If the  user discards the settings changes by  dismissing the UI
// with the  "Cancel" button;  the reject()  operation is  called. The
// reject() operation calls initialize_models()  which will revert all
// the  UI visible  state  to  the values  as  at  the initial  exec()
// operation.  No   changes  are  moved   into  the  data   fields  in
// Configuration::impl that  reflect the  settings state  published by
// the public interface (Configuration.hpp).
//
// 5) If  the user accepts the  settings changes by dismissing  the UI
// with the "OK" button; the  accept() operation is called which calls
// the validate() operation  again and, if it passes,  the fields that
// are used  to deliver  the settings  state are  updated from  the UI
// control models  or other temporary  state variables. At the  end of
// the accept()  operation, just  before hiding  the UI  and returning
// control to the caller; the new  settings values are stored into the
// settings database by a call to the write_settings() operation, thus
// ensuring that  settings changes are  saved even if  the application
// crashes or is subsequently killed.
//
// 6)  On  destruction,  which   only  happens  when  the  application
// terminates,  the settings  are saved  to the  settings database  by
// calling the  write_settings() operation. This is  largely redundant
// but is still done to save the default values of any new settings on
// an initial run.
//
// To add a new setting:
//
// 1) Update the UI with the new widget to view and change the value.
//
// 2)  Add  a member  to  Configuration::impl  to store  the  accepted
// setting state. If the setting state is dynamic; add a new signal to
// broadcast the setting value.
//
// 3) Add a  query method to the  public interface (Configuration.hpp)
// to access the  new setting value. If the settings  is dynamic; this
// step  is optional  since  value  changes will  be  broadcast via  a
// signal.
//
// 4) Add a forwarding operation to implement the new query (3) above.
//
// 5)  Add a  settings read  call to  read_settings() with  a sensible
// default value. If  the setting value is dynamic, add  a signal emit
// call to broadcast the setting value change.
//
// 6) Add  code to  initialize_models() to  load the  widget control's
// data model with the current value.
//
// 7) If there is no convenient data model field, add a data member to
// store the proposed new value. Ensure  this member has a valid value
// on exit from read_settings().
//
// 8)  Add  any  required  inter-field validation  to  the  validate()
// operation.
//
// 9) Add code to the accept()  operation to extract the setting value
// from  the  widget   control  data  model  and  load   it  into  the
// Configuration::impl  member  that  reflects  the  publicly  visible
// setting state. If  the setting value is dynamic; add  a signal emit
// call to broadcast any changed state of the setting.
//
// 10) Add  a settings  write call  to save the  setting value  to the
// settings database.
//

#include <stdexcept>
#include <iterator>
#include <algorithm>
#include <functional>
#include <limits>
#include <cmath>

#include <QApplication>
#include <QCursor>
#include <QMetaType>
#include <QList>
#include <QPair>
#include <QVariant>
#include <QSettings>
#include <QAudioDeviceInfo>
#include <QAudioInput>
#include <QDialog>
#include <QAction>
#include <QFileDialog>
#include <QDir>
#include <QTemporaryFile>
#include <QFormLayout>
#include <QString>
#include <QStringList>
#include <QStringListModel>
#include <QLineEdit>
#include <QRegularExpression>
#include <QRegularExpressionValidator>
#include <QIntValidator>
#include <QThread>
#include <QTimer>
#include <QStandardPaths>
#include <QFont>
#include <QFontDialog>
#include <QComboBox>
#include <QScopedPointer>
#include <QNetworkInterface>
#include <QHostInfo>
#include <QHostAddress>
#include <QStandardItem>
#include <QDebug>
#include <QDateTimeEdit>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <QSerialPortInfo>
#include <vector>
#include <utility>
#include <iostream>

#include "pimpl_impl.hpp"
#include "Logger.hpp"
#include "qt_helpers.hpp"
#include "MetaDataRegistry.hpp"
#include "SettingsGroup.hpp"
#include "widgets/FrequencyLineEdit.hpp"
#include "widgets/FrequencyDeltaLineEdit.hpp"
#include "item_delegates/CandidateKeyFilter.hpp"
#include "item_delegates/ForeignKeyDelegate.hpp"
#include "item_delegates/FrequencyDelegate.hpp"
#include "item_delegates/FrequencyDeltaDelegate.hpp"
#include "item_delegates/MessageItemDelegate.hpp"
#include "Transceiver/TransceiverFactory.hpp"
#include "Transceiver/Transceiver.hpp"
#include "models/Bands.hpp"
#include "models/IARURegions.hpp"
#include "models/Modes.hpp"
#include "models/FrequencyList.hpp"
#include "models/StationList.hpp"
#include "Network/NetworkServerLookup.hpp"
#include "Network/FoxVerifier.hpp"
#include "widgets/MessageBox.hpp"
#include "validators/MaidenheadLocatorValidator.hpp"
#include "validators/CallsignValidator.hpp"
#include "Network/LotWUsers.hpp"
#include "Network/Cloudlog.hpp"
#include "models/DecodeHighlightingModel.hpp"
#include "logbook/logbook.h"
#include "widgets/LazyFillComboBox.hpp"
#include "Network/FileDownload.hpp"

#include "ui_Configuration.h"
#include "moc_Configuration.cpp"

namespace
{
  // these undocumented flag values when stored in (Qt::UserRole - 1)
  // of a ComboBox item model index allow the item to be enabled or
  // disabled
  int const combo_box_item_enabled (32 | 1);
  int const combo_box_item_disabled (0);

//  QRegExp message_alphabet {"[- A-Za-z0-9+./?]*"};
  QRegularExpression message_alphabet {"[- @A-Za-z0-9+./?#<>;$]*"};
  QRegularExpression RTTY_roundup_exchange_re {
    R"(
        (
           AL|AZ|AR|CA|CO|CT|DE|FL|GA      # 48 contiguous states
          |ID|IL|IN|IA|KS|KY|LA|ME|MD
          |MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ
          |NM|NY|NC|ND|OH|OK|OR|PA|RI|SC
          |SD|TN|TX|UT|VT|VA|WA|WV|WI|WY
          |NB|NS|QC|ON|MB|SK|AB|BC|NWT|NF  # VE provinces
          |LB|NU|YT|PEI
          |DC                              # District of Columbia
          |DX                              # anyone else
          |SCC                             # Slovenia Contest Club contest
          |DR|FR|GD|GR|OV|ZH|ZL            # Dutch provinces (also FL,NH,UT,NB,LB)
          |X01|X02|X03|X04|X05|X06|X07     # 99 neutral exchanges
          |X08|X09|X10|X11|X12|X13|X14
          |X15|X16|X17|X18|X19|X20|X21
          |X22|X23|X24|X25|X26|X27|X28
          |X29|X30|X31|X32|X33|X34|X35
          |X36|X37|X38|X39|X40|X41|X42
          |X43|X44|X45|X46|X47|X48|X49
          |X50|X51|X52|X53|X54|X55|X56
          |X57|X58|X59|X60|X61|X62|X63
          |X64|X65|X66|X67|X68|X69|X70
          |X71|X72|X73|X74|X75|X76|X77
          |X78|X79|X80|X81|X82|X83|X84
          |X85|X86|X87|X88|X89|X90|X91
          |X92|X93|X94|X95|X96|X97|X98
          |X99
          |[0][0][0][1-9]                  # 4-digit numbers
          |[0][0-9][1-9][0-9]              # between 0001
          |[1-7][0-9][0-9][0-9]            # and 7999
        )
      )", QRegularExpression::CaseInsensitiveOption | QRegularExpression::ExtendedPatternSyntaxOption};

  QRegularExpression field_day_exchange_re {
    R"(
        (
           [1-9]                          # # transmitters (1 to 32 inc.)
          |[0-2]\d
          |3[0-2]
        )
        [A-F]\ *                          # class and optional space
        (
           AB|AK|AL|AR|AZ|BC|CO|CT|DE|EB  # ARRL/RAC section
          |EMA|ENY|EPA|EWA|GA|GH|IA|ID
          |IL|IN|KS|KY|LA|LAX|MB|MDC|ME
          |MI|MN|MO|MS|MT|NB|NC|ND|NE|NFL
          |NH|NL|NLI|NM|NNJ|NNY|NS|NTX|NV
          |OH|OK|ONE|ONN|ONS|OR|ORG|PAC
          |PE|PR|QC|RI|SB|SC|SCV|SD|SDG
          |SF|SFL|SJV|SK|SNJ|STX|SV|TER
          |TN|UT|VA|VI|VT|WCF|WI|WMA|WNY
          |WPA|WTX|WV|WWA|WY
          |DX                             # anyone else
        )
      )", QRegularExpression::CaseInsensitiveOption | QRegularExpression::ExtendedPatternSyntaxOption};

  // Magic numbers for file validation
  constexpr quint32 qrg_magic {0xadbccbdb};
  constexpr quint32 qrg_version {101}; // M.mm
  constexpr quint32 qrg_version_100 {100};
}


//
// Dialog to get a new Frequency item
//
class FrequencyDialog final
  : public QDialog
{
  Q_OBJECT

public:
  using Item = FrequencyList_v2_101::Item;

  explicit FrequencyDialog (IARURegions * regions_model, Modes * modes_model, QWidget * parent = nullptr)
    : QDialog {parent}
  {
    start_date_time_edit_ = new QDateTimeEdit(QDateTime(QDate::currentDate(), QTime(0,0,0,0), Qt::UTC), parent);
    end_date_time_edit_ = new QDateTimeEdit(QDateTime(QDate::currentDate().addDays(2), QTime(0,0,0,0), Qt::UTC), parent);

    enable_dates_checkbox_ = new QCheckBox {tr ("")};
    start_date_time_edit_->setDisplayFormat("yyyy.MM.dd hh:mm:ss 'UTC'");
    start_date_time_edit_->setTimeSpec(Qt::UTC);
    start_date_time_edit_->setMinimumDate(QDate::currentDate().addDays(-365));

    end_date_time_edit_->setDisplayFormat("yyyy.MM.dd hh:mm:ss 'UTC'");
    end_date_time_edit_->setTimeSpec(Qt::UTC);
    end_date_time_edit_->setMinimumDate(QDate::currentDate().addDays(-365));
    preferred_frequency_checkbox_ = new QCheckBox {tr ("")};

    setWindowTitle (QApplication::applicationName () + " - " +
                    tr ("Add Frequency"));

    region_combo_box_.setModel (regions_model);
    mode_combo_box_.setModel (modes_model);

    auto form_layout = new QFormLayout ();
    form_layout->addRow (tr ("IARU &Region:"), &region_combo_box_);
    form_layout->addRow (tr ("&Mode:"), &mode_combo_box_);
    form_layout->addRow (tr ("&Frequency (MHz):"), &frequency_line_edit_);
    form_layout->addRow (tr ("&Preferred for Band/Mode:"), preferred_frequency_checkbox_);
    form_layout->addRow (tr ("&Description:"), &description_line_edit_);
    form_layout->addRow (tr ("&Enable Date Range:"), enable_dates_checkbox_);
    form_layout->addRow (tr ("S&tart:"), start_date_time_edit_);
    form_layout->addRow (tr ("&End:"), end_date_time_edit_);
    form_layout->addRow (tr ("&Source:"), &source_line_edit_);

    auto main_layout = new QVBoxLayout (this);
    main_layout->addLayout (form_layout);

    button_box = new QDialogButtonBox {QDialogButtonBox::Ok | QDialogButtonBox::Cancel};
    main_layout->addWidget (button_box);

    connect (button_box, &QDialogButtonBox::accepted, this, &FrequencyDialog::accept);
    connect (button_box, &QDialogButtonBox::rejected, this, &FrequencyDialog::reject);
    connect (start_date_time_edit_, &QDateTimeEdit::dateTimeChanged, this, &FrequencyDialog::checkSaneDates);
    connect (end_date_time_edit_, &QDateTimeEdit::dateTimeChanged, this, &FrequencyDialog::checkSaneDates);
    connect (enable_dates_checkbox_, &QCheckBox::stateChanged, this, &FrequencyDialog::toggleValidity);
    toggleValidity();
  }

    void toggleValidity()
    {
        start_date_time_edit_->setEnabled(enable_dates_checkbox_->isChecked());
        end_date_time_edit_->setEnabled(enable_dates_checkbox_->isChecked());
        checkSaneDates();
    }

    void checkSaneDates()
    {
        if (enable_dates_checkbox_->isChecked() && start_date_time_edit_->dateTime().isValid() && end_date_time_edit_->dateTime().isValid())
        {
            if (start_date_time_edit_->dateTime() > end_date_time_edit_->dateTime())
            {
                QMessageBox::warning(this, tr("Invalid Date Range"), tr("Start date must be before end date"));
                button_box->button(QDialogButtonBox::Ok)->setEnabled(false);
                return;
            }
        }
        button_box->button(QDialogButtonBox::Ok)->setEnabled(true);
    }

  Item item () const
  {
    QDateTime start_time = enable_dates_checkbox_->isChecked() ? start_date_time_edit_->dateTime() : QDateTime();
    QDateTime end_time = enable_dates_checkbox_->isChecked() ? end_date_time_edit_->dateTime()  : QDateTime();
    return {
            frequency_line_edit_.frequency(),
            Modes::value(mode_combo_box_.currentText()),
            IARURegions::value(region_combo_box_.currentText()),
            description_line_edit_.text(), source_line_edit_.text(),
            start_time,
            end_time,
            preferred_frequency_checkbox_->isChecked()
    };
  }

private:
  QComboBox region_combo_box_;
  QComboBox mode_combo_box_;
  FrequencyLineEdit frequency_line_edit_;
  QLineEdit description_line_edit_;
  QLineEdit source_line_edit_;
  QDialogButtonBox * button_box;
  QCheckBox *enable_dates_checkbox_;
  QCheckBox *preferred_frequency_checkbox_;
  QDateTimeEdit *end_date_time_edit_;
  QDateTimeEdit *start_date_time_edit_;
};


//
// Dialog to get a new Station item
//
class StationDialog final
  : public QDialog
{
  Q_OBJECT

public:
  explicit StationDialog (StationList const * stations, Bands * bands, QWidget * parent = nullptr)
    : QDialog {parent}
    , filtered_bands_ {new CandidateKeyFilter {bands, stations, 0, 0}}
  {
    setWindowTitle (QApplication::applicationName () + " - " + tr ("Add Station"));

    band_.setModel (filtered_bands_.data ());
      
    auto form_layout = new QFormLayout ();
    form_layout->addRow (tr ("&Band:"), &band_);
    form_layout->addRow (tr ("&Offset (MHz):"), &delta_);
    form_layout->addRow (tr ("&Antenna:"), &description_);

    auto main_layout = new QVBoxLayout (this);
    main_layout->addLayout (form_layout);

    auto button_box = new QDialogButtonBox {QDialogButtonBox::Ok | QDialogButtonBox::Cancel};
    main_layout->addWidget (button_box);

    connect (button_box, &QDialogButtonBox::accepted, this, &StationDialog::accept);
    connect (button_box, &QDialogButtonBox::rejected, this, &StationDialog::reject);

    if (delta_.text ().isEmpty ())
      {
        delta_.setText ("0");
      }
  }

  StationList::Station station () const
  {
    return {band_.currentText (), delta_.frequency_delta (), description_.text ()};
  }

  int exec () override
  {
    filtered_bands_->set_active_key ();
    return QDialog::exec ();
  }

private:
  QScopedPointer<CandidateKeyFilter> filtered_bands_;

  QComboBox band_;
  FrequencyDeltaLineEdit delta_;
  QLineEdit description_;
};

class RearrangableMacrosModel
  : public QStringListModel
{
public:
  Qt::ItemFlags flags (QModelIndex const& index) const override
  {
    auto flags = QStringListModel::flags (index);
    if (index.isValid ())
      {
        // disallow drop onto existing items
        flags &= ~Qt::ItemIsDropEnabled;
      }
    return flags;
  }
};




// Internal implementation of the Configuration class.
class Configuration::impl final
  : public QDialog
{
  Q_OBJECT;

public:
  using FrequencyDelta = Radio::FrequencyDelta;
  using port_type = Configuration::port_type;
  using audio_info_type = QPair<QAudioDeviceInfo , QList<QVariant> >;

  explicit impl (Configuration * self
                 , QNetworkAccessManager * network_manager
                 , QDir const& temp_directory
                 , QSettings * settings
                 , LogBook * logbook
                 , QWidget * parent);
  ~impl ();

  bool have_rig ();

  void transceiver_frequency (Frequency);
  void transceiver_tx_frequency (Frequency);
  void transceiver_mode (MODE);
  void transceiver_ptt (bool);
  void transceiver_audio (bool);
  void transceiver_tune (bool);
  void transceiver_period (double);
  void transceiver_blocksize (qint32);
  void transceiver_modulator_start (QString, unsigned, double, double, double, bool, bool, double, double);
  void transceiver_modulator_stop (bool);
  void transceiver_spread (double);
  void transceiver_nsym (int);
  void transceiver_trfrequency (double);
  void transceiver_volume (double);
  void transceiver_txvolume (double);
  void sync_transceiver (bool force_signal);

  Q_SLOT int exec () override;
  Q_SLOT void accept () override;
  Q_SLOT void reject () override;
  Q_SLOT void done (int) override;

private:
  typedef QList<QAudioDeviceInfo> AudioDevices;

  void read_settings ();
  void write_settings ();

  void find_audio_devices ();
  QAudioDeviceInfo find_audio_device (QAudio::Mode, QComboBox *, QString const& device_name);
  void load_audio_devices (QAudio::Mode, QComboBox *, QAudioDeviceInfo *);
  void update_audio_channels (QComboBox const *, int, QComboBox *, bool);

  void load_network_interfaces (CheckableItemComboBox *, QStringList current);
  Q_SLOT void validate_network_interfaces (QString const&);
  QStringList get_selected_network_interfaces (CheckableItemComboBox *);
  Q_SLOT void host_info_results (QHostInfo);
  void check_multicast (QHostAddress const&);

  void find_tab (QWidget *);

  void initialize_models ();
  bool split_mode () const
  {
    return
      (WSJT_RIG_NONE_CAN_SPLIT || !rig_is_dummy_) &&
      (rig_params_.split_mode != TransceiverFactory::split_mode_none);
  }
  void set_cached_mode ();
  bool open_rig (bool force = false);
  //bool set_mode ();
  void close_rig ();
  TransceiverFactory::ParameterPack gather_rig_data ();
  void enumerate_rigs ();
  void set_rig_invariants ();
  bool validate ();
  void fill_port_combo_box (QComboBox *);
  Frequency apply_calibration (Frequency) const;
  Frequency remove_calibration (Frequency) const;

  void delete_frequencies ();
  void load_frequencies ();
  void merge_frequencies ();
  void save_frequencies ();
  void reset_frequencies ();
  void insert_frequency ();
  void size_frequency_table_columns();

    FrequencyList_v2_101::FrequencyItems read_frequencies_file (QString const&);

  void delete_stations ();
  void insert_station ();

  Q_SLOT void on_font_push_button_clicked ();
  Q_SLOT void on_decoded_text_font_push_button_clicked ();
  Q_SLOT void on_PTT_port_combo_box_activated (int);
  Q_SLOT void on_CAT_port_combo_box_activated (int);
  Q_SLOT void on_CAT_serial_baud_combo_box_currentIndexChanged (int);
  Q_SLOT void on_CAT_data_bits_button_group_buttonClicked (int);
  Q_SLOT void on_CAT_stop_bits_button_group_buttonClicked (int);
  Q_SLOT void on_CAT_handshake_button_group_buttonClicked (int);
  Q_SLOT void on_CAT_poll_interval_spin_box_valueChanged (int);
  Q_SLOT void on_split_mode_button_group_buttonClicked (int);
  Q_SLOT void on_test_CAT_push_button_clicked ();
  Q_SLOT void on_test_PTT_push_button_clicked (bool checked);
  Q_SLOT void on_pbTestCloudlog_clicked ();
  Q_SLOT void on_gbCloudlog_clicked ();
  Q_SLOT void on_force_DTR_combo_box_currentIndexChanged (int);
  Q_SLOT void on_force_RTS_combo_box_currentIndexChanged (int);
  Q_SLOT void on_rig_combo_box_currentIndexChanged (int);
  Q_SLOT void on_refresh_push_button_clicked ();
  Q_SLOT void on_tci_audio_check_box_clicked(bool checked);
  Q_SLOT void on_TCI_spin_box_valueChanged(double a);
  Q_SLOT void on_add_macro_push_button_clicked (bool = false);
  Q_SLOT void on_delete_macro_push_button_clicked (bool = false);
  Q_SLOT void on_PTT_method_button_group_buttonClicked (int);
  Q_SLOT void on_add_macro_line_edit_editingFinished ();
  Q_SLOT void delete_macro ();
  void delete_selected_macros (QModelIndexList);
  void after_CTY_downloaded();
  void set_CTY_DAT_version(QString const& version);
  void error_during_CTY_download (QString const& reason);
  void after_CALL3_downloaded();
  void error_during_CALL3_download (QString const& reason);
  void read_CALL3_version();
  Q_SLOT void on_udp_server_line_edit_textChanged (QString const&);
  Q_SLOT void on_udp_server_line_edit_editingFinished ();
  Q_SLOT void on_save_path_select_push_button_clicked (bool);
  Q_SLOT void on_azel_path_select_push_button_clicked (bool);
  Q_SLOT void on_calibration_intercept_spin_box_valueChanged (double);
  Q_SLOT void handle_leavingSettings ();
  Q_SLOT void on_calibration_slope_ppm_spin_box_valueChanged (double);
  Q_SLOT void handle_transceiver_tciframeswritten (qint64);
  Q_SLOT void handle_transceiver_tci_mod_active (bool);
  Q_SLOT void handle_transceiver_update (TransceiverState const&, unsigned sequence_number);
  Q_SLOT void handle_transceiver_failure (QString const& reason);
  Q_SLOT void on_DXCC_check_box_clicked(bool checked);
  Q_SLOT void on_PWR_and_SWR_check_box_clicked(bool checked);
  Q_SLOT void on_cbHighDPI_clicked(bool checked);
  Q_SLOT void on_reset_highlighting_to_defaults_push_button_clicked (bool);
  Q_SLOT void on_reset_highlighting_to_defaults2_push_button_clicked (bool);
  Q_SLOT void on_rescan_log_push_button_clicked (bool);
  Q_SLOT void on_CTY_download_button_clicked (bool);
  Q_SLOT void on_CALL3_download_button_clicked (bool);
  Q_SLOT void on_CALL3_EME_download_button_clicked (bool);
  Q_SLOT void on_LotW_CSV_fetch_push_button_clicked (bool);
  Q_SLOT void on_hamlib_download_button_clicked (bool);
  Q_SLOT void on_revert_update_button_clicked (bool);
  Q_SLOT void on_gbSpecialOpActivity_clicked (bool);
  Q_SLOT void on_rbFox_clicked (bool);
  Q_SLOT void on_rbHound_clicked (bool);
  Q_SLOT void on_rbNA_VHF_Contest_clicked (bool);
  Q_SLOT void on_rbEU_VHF_Contest_clicked (bool);
  Q_SLOT void on_rbWW_DIGI_clicked (bool);
  Q_SLOT void on_rbQ65pileup_clicked (bool);
  Q_SLOT void on_rbField_Day_clicked (bool);
  Q_SLOT void on_rbRTTY_Roundup_clicked (bool);
  Q_SLOT void on_rbARRL_Digi_clicked (bool);
  Q_SLOT void on_cbSuperFox_clicked (bool);
  Q_SLOT void on_cbContestName_clicked (bool);
  Q_SLOT void on_cbOTP_clicked (bool);
  Q_SLOT void on_cbShowOTP_clicked (bool);
  Q_SLOT void on_cb_NCCC_Sprint_clicked (bool);
  void error_during_hamlib_download (QString const& reason);
  void after_hamlib_downloaded();
  void display_file_information();
  void check_visibility();

  Q_SLOT void on_cbx2ToneSpacing_clicked(bool);
  Q_SLOT void on_cbx4ToneSpacing_clicked(bool);
  Q_SLOT void on_prompt_to_log_check_box_clicked(bool);
  Q_SLOT void on_cbAutoLog_clicked(bool);
  Q_SLOT void on_Field_Day_Exchange_editingFinished ();
  Q_SLOT void on_RTTY_Exchange_editingFinished ();
  Q_SLOT void on_OTPUrl_textEdited (QString const&);
  Q_SLOT void on_OTPSeed_textEdited (QString const&);
  Q_SLOT void on_cbSortAlphabetically_clicked(bool);
  Q_SLOT void on_cbHideCARD_clicked(bool);
  Q_SLOT void on_Contest_Name_editingFinished ();
  Q_SLOT void on_Blacklist1_editingFinished ();
  Q_SLOT void on_Blacklist2_editingFinished ();
  Q_SLOT void on_Blacklist3_editingFinished ();
  Q_SLOT void on_Blacklist4_editingFinished ();
  Q_SLOT void on_Blacklist5_editingFinished ();
  Q_SLOT void on_Blacklist6_editingFinished ();
  Q_SLOT void on_Blacklist7_editingFinished ();
  Q_SLOT void on_Blacklist8_editingFinished ();
  Q_SLOT void on_Blacklist9_editingFinished ();
  Q_SLOT void on_Blacklist10_editingFinished ();
  Q_SLOT void on_Blacklist11_editingFinished ();
  Q_SLOT void on_Blacklist12_editingFinished ();
  Q_SLOT void on_Whitelist1_editingFinished ();
  Q_SLOT void on_Whitelist2_editingFinished ();
  Q_SLOT void on_Whitelist3_editingFinished ();
  Q_SLOT void on_Whitelist4_editingFinished ();
  Q_SLOT void on_Whitelist5_editingFinished ();
  Q_SLOT void on_Whitelist6_editingFinished ();
  Q_SLOT void on_Whitelist7_editingFinished ();
  Q_SLOT void on_Whitelist8_editingFinished ();
  Q_SLOT void on_Whitelist9_editingFinished ();
  Q_SLOT void on_Whitelist10_editingFinished ();
  Q_SLOT void on_Whitelist11_editingFinished ();
  Q_SLOT void on_Whitelist12_editingFinished ();
  Q_SLOT void on_Pass1_editingFinished ();
  Q_SLOT void on_Pass2_editingFinished ();
  Q_SLOT void on_Pass3_editingFinished ();
  Q_SLOT void on_Pass4_editingFinished ();
  Q_SLOT void on_Pass5_editingFinished ();
  Q_SLOT void on_Pass6_editingFinished ();
  Q_SLOT void on_Pass7_editingFinished ();
  Q_SLOT void on_Pass8_editingFinished ();
  Q_SLOT void on_Pass9_editingFinished ();
  Q_SLOT void on_Pass10_editingFinished ();
  Q_SLOT void on_Pass11_editingFinished ();
  Q_SLOT void on_Pass12_editingFinished ();
  Q_SLOT void on_Territory1_editingFinished ();
  Q_SLOT void on_Territory2_editingFinished ();
  Q_SLOT void on_Territory3_editingFinished ();
  Q_SLOT void on_Territory4_editingFinished ();
  Q_SLOT void on_highlight_orange_callsigns_editingFinished ();
  Q_SLOT void on_highlight_blue_callsigns_editingFinished ();

  // typenames used as arguments must match registered type names :(
  Q_SIGNAL void start_transceiver (unsigned seqeunce_number) const;
  Q_SIGNAL void set_transceiver (Transceiver::TransceiverState const&,
                                 unsigned sequence_number) const;
  Q_SIGNAL void stop_transceiver () const;

  Configuration * const self_;	// back pointer to public interface

  QThread * transceiver_thread_;
  TransceiverFactory transceiver_factory_;
  QList<QMetaObject::Connection> rig_connections_;

  QScopedPointer<Ui::configuration_dialog> ui_;

  QNetworkAccessManager * network_manager_;
  QSettings * settings_;
  LogBook * logbook_;

  QDir doc_dir_;
  QDir data_dir_;
  QDir temp_dir_;
  QDir writeable_data_dir_;
  QDir default_save_directory_;
  QDir save_directory_;
  QDir default_azel_directory_;
  QDir azel_directory_;

  QFont font_;
  QFont next_font_;

  QFont decoded_text_font_;
  QFont next_decoded_text_font_;

  LotWUsers lotw_users_;
  Cloudlog cloudlog_;

  bool restart_sound_input_device_;
  bool restart_sound_output_device_;
  bool restart_tci_device_;

  Type2MsgGen type_2_msg_gen_;

  QStringListModel macros_;
  RearrangableMacrosModel next_macros_;
  QAction * macro_delete_action_;

  Bands bands_;
  IARURegions regions_;
  IARURegions::Region region_;
  Modes modes_;
  FrequencyList_v2_101 frequencies_;
  FrequencyList_v2_101 next_frequencies_;
  StationList stations_;
  StationList next_stations_;
  FrequencyDelta current_offset_;
  FrequencyDelta current_tx_offset_;

  QAction * frequency_delete_action_;
  QAction * frequency_insert_action_;
  QAction * load_frequencies_action_;
  QAction * save_frequencies_action_;
  QAction * merge_frequencies_action_;
  QAction * reset_frequencies_action_;
  FrequencyDialog * frequency_dialog_;

  QAction station_delete_action_;
  QAction station_insert_action_;
  StationDialog * station_dialog_;

  DecodeHighlightingModel decode_highlighing_model_;
  DecodeHighlightingModel next_decode_highlighing_model_;
  bool highlight_by_mode_;
  bool highlight_only_fields_;
  bool include_WAE_entities_;
  bool highlight_73_;
  bool highlight_orange_;
  bool highlight_blue_;
  bool bSpecialOp_;
  bool alternate_erase_button_;
  bool show_country_names_;
  int LotW_days_since_upload_;

  TransceiverFactory::ParameterPack rig_params_;
  TransceiverFactory::ParameterPack saved_rig_params_;
  TransceiverFactory::Capabilities::PortType last_port_type_;
  bool rig_is_dummy_;
  bool is_tci_;
  bool rig_active_;
  bool have_rig_;
  bool rig_changed_;
  TransceiverState cached_rig_state_;
  int rig_resolution_;          // see Transceiver::resolution signal
  CalibrationParams calibration_;
  bool frequency_calibration_disabled_; // not persistent
  unsigned transceiver_command_number_;
  QString dynamic_grid_;

  // configuration fields that we publish
  QString my_callsign_;
  QString my_grid_;
  QString FD_exchange_;
  QString RTTY_exchange_;
  QString Contest_Name_;
  QString Blacklist1_;
  QString Blacklist2_;
  QString Blacklist3_;
  QString Blacklist4_;
  QString Blacklist5_;
  QString Blacklist6_;
  QString Blacklist7_;
  QString Blacklist8_;
  QString Blacklist9_;
  QString Blacklist10_;
  QString Blacklist11_;
  QString Blacklist12_;
  QString Whitelist1_;
  QString Whitelist2_;
  QString Whitelist3_;
  QString Whitelist4_;
  QString Whitelist5_;
  QString Whitelist6_;
  QString Whitelist7_;
  QString Whitelist8_;
  QString Whitelist9_;
  QString Whitelist10_;
  QString Whitelist11_;
  QString Whitelist12_;
  QString Pass1_;
  QString Pass2_;
  QString Pass3_;
  QString Pass4_;
  QString Pass5_;
  QString Pass6_;
  QString Pass7_;
  QString Pass8_;
  QString Pass9_;
  QString Pass10_;
  QString Pass11_;
  QString Pass12_;
  QString Territory1_;
  QString Territory2_;
  QString Territory3_;
  QString Territory4_;
  QString highlight_orange_callsigns_;
  QString highlight_blue_callsigns_;
  QString hamlib_backed_up_;
  QString cloudLogApiUrl_;
  QString cloudLogApiKey_;

  QString OTPUrl_;
  QString OTPSeed_;
  bool  OTPEnabled_;
  bool  ShowOTP_;
  qint32 OTPinterval_;

  qint32 id_interval_;
  qint32 align_steps_;
  qint32 align_steps2_;
  qint32 ntrials_;
  qint32 volume_;
  qint32 aggressive_;
  qint32 RxBandwidth_;
  qint32 cloudLogStationID_;
  bool PWR_and_SWR_;
  bool check_SWR_;
  double degrade_;
  double txDelay_;
  bool tci_audio_;
  bool id_after_73_;
  bool tx_QSY_allowed_;
  bool progressBar_red_;
  bool spot_to_psk_reporter_;
  bool psk_reporter_tcpip_;
  bool monitor_off_at_startup_;
  bool monitor_last_used_;
  bool log_as_RTTY_;
  bool report_in_comments_;
  bool specOp_in_comments_;
  bool prompt_to_log_;
  bool autoLog_;
  bool contestingOnly_;
  bool ZZ00_;
  bool log4digitGrids_;
  bool decodes_from_top_;
  bool insert_blank_;
  bool detailed_blank_;
  bool DXCC_;
  bool gridMap_;
  bool gridMapAll_;
  bool ppfx_;
  bool miles_;
  bool quick_call_;
  bool disable_TX_on_73_;
  bool force_call_1st_;
  bool alternate_bindings_;
  int watchdog_;
  int tune_watchdog_time_;
  bool tune_watchdog_;
  bool TX_messages_;
  bool enable_VHF_features_;
  bool decode_at_52s_;
  bool kHz_without_k_;
  bool button_coloring_disabled_;
  bool Wait_features_enabled_;
  bool showDistance_;
  bool showAzimuth_;
  bool align_;
  bool repeat_Tx_;
  bool auto_astro_;
  bool single_decode_;
  bool twoPass_;
  bool highDPI_;
  bool largerTabWidget_;
  bool bSuperFox_;
  bool Individual_Contest_Name_;
  bool NCCC_Sprint_;
  bool Blacklisted_;
  bool Whitelisted_;
  bool AlwaysPass_;
  bool filters_for_Wait_and_Pounce_only_;
  bool filters_for_word2_;
  bool twoDays_;
  bool bCloudLog_;
  int  SelectedActivity_;
  bool x2ToneSpacing_;
  bool x4ToneSpacing_;
  bool use_dynamic_grid_;
  QString opCall_;
  QString udp_server_name_;
  bool udp_server_name_edited_;
  int dns_lookup_id_;
  port_type udp_server_port_;
  QStringList udp_interface_names_;
  QString loopback_interface_name_;
  int udp_TTL_;
  QString n1mm_server_name_;
  port_type n1mm_server_port_;
  bool broadcast_to_n1mm_;
  bool accept_udp_requests_;
  bool udpWindowToFront_;
  bool udpWindowRestore_;
  DataMode data_mode_;
  bool bLowSidelobes_;
  bool sortAlphabetically_;
  bool hideCARD_;
  bool AzElExtraLines_;
  bool pwrBandTxMemory_;
  bool pwrBandTuneMemory_;
  bool highlight_DXcall_;
  bool clear_DXcall_;
  bool highlight_DXgrid_;
  bool clear_DXgrid_;
  bool erase_BandActivity_;
  bool set_RXtoTX_;
  bool alert_CQ_;
  bool alert_MyCall_;
  bool alert_DXCC_;
  bool alert_DXCCOB_;
  bool alert_Grid_;
  bool alert_GridOB_;
  bool alert_Continent_;
  bool alert_ContinentOB_;
  bool alert_CQZ_;
  bool alert_CQZOB_;
  bool alert_ITUZ_;
  bool alert_ITUZOB_;
  bool alert_DXcall_;
  bool alert_QSYmessage_;
  bool alert_Enabled_;

  QAudioDeviceInfo audio_input_device_;
  QAudioDeviceInfo next_audio_input_device_;
  AudioDevice::Channel audio_input_channel_;
  AudioDevice::Channel next_audio_input_channel_;
  QAudioDeviceInfo audio_output_device_;
  QAudioDeviceInfo next_audio_output_device_;
  AudioDevice::Channel audio_output_channel_;
  AudioDevice::Channel next_audio_output_channel_;
  FileDownload cty_download;
  
  bool default_audio_input_device_selected_;
  bool default_audio_output_device_selected_;
  
  friend class Configuration;
};

#include "Configuration.moc"


// delegate to implementation class
Configuration::Configuration (QNetworkAccessManager * network_manager, QDir const& temp_directory,
                              QSettings * settings, LogBook * logbook, QWidget * parent)
  : m_ {this, network_manager, temp_directory, settings, logbook, parent}
{
}

Configuration::~Configuration ()
{
}
QDir Configuration::doc_dir () const {return m_->doc_dir_;}
QDir Configuration::data_dir () const {return m_->data_dir_;}
QDir Configuration::writeable_data_dir () const {return m_->writeable_data_dir_;}
QDir Configuration::temp_dir () const {return m_->temp_dir_;}

void Configuration::select_tab (int index) {m_->ui_->configuration_tabs->setCurrentIndex (index);}
int Configuration::exec () {return m_->exec ();}
bool Configuration::is_active () const {return m_->isVisible ();}

QAudioDeviceInfo const& Configuration::audio_input_device () const {return m_->audio_input_device_;}
AudioDevice::Channel Configuration::audio_input_channel () const {return m_->audio_input_channel_;}
QAudioDeviceInfo const& Configuration::audio_output_device () const {return m_->audio_output_device_;}
AudioDevice::Channel Configuration::audio_output_channel () const {return m_->audio_output_channel_;}
bool Configuration::restart_audio_input () const {return m_->restart_sound_input_device_;}
bool Configuration::restart_audio_output () const {return m_->restart_sound_output_device_;}
bool Configuration::restart_tci () const {return m_->restart_tci_device_;}
auto Configuration::type_2_msg_gen () const -> Type2MsgGen {return m_->type_2_msg_gen_;}
QString Configuration::my_callsign () const {return m_->my_callsign_;}
QFont Configuration::text_font () const {return m_->font_;}
QFont Configuration::decoded_text_font () const {return m_->decoded_text_font_;}
qint32 Configuration::id_interval () const {return m_->id_interval_;}
qint32 Configuration::align_steps () const {return m_->align_steps_;}
qint32 Configuration::align_steps2 () const {return m_->align_steps2_;}
qint32 Configuration::ntrials() const {return m_->ntrials_;}
qint32 Configuration::volume() const {return m_->volume_;}
qint32 Configuration::aggressive() const {return m_->aggressive_;}
double Configuration::degrade() const {return m_->degrade_;}
double Configuration::txDelay() const {return m_->txDelay_;}
qint32 Configuration::RxBandwidth() const {return m_->RxBandwidth_;}
bool Configuration::tci_audio () const {return m_->tci_audio_;}
bool Configuration::id_after_73 () const {return m_->id_after_73_;}
bool Configuration::tx_QSY_allowed () const {return m_->tx_QSY_allowed_;}
bool Configuration::progressBar_red () const {return m_->progressBar_red_;}
bool Configuration::spot_to_psk_reporter () const
{
  // rig must be open and working to spot externally
  return is_transceiver_online () && m_->spot_to_psk_reporter_;
}
bool Configuration::psk_reporter_tcpip () const {return m_->psk_reporter_tcpip_;}
bool Configuration::monitor_off_at_startup () const {return m_->monitor_off_at_startup_;}
bool Configuration::monitor_last_used () const {return m_->rig_is_dummy_ || m_->monitor_last_used_;}
bool Configuration::log_as_RTTY () const {return m_->log_as_RTTY_;}
bool Configuration::report_in_comments () const {return m_->report_in_comments_;}
bool Configuration::specOp_in_comments () const {return m_->specOp_in_comments_;}
bool Configuration::cloudlog_enabled () const {return m_->bCloudLog_;}
QString Configuration::cloudlog_api_url () const {return m_->cloudLogApiUrl_;}
QString Configuration::cloudlog_api_key () const {return m_->cloudLogApiKey_;}
qint32 Configuration::cloudlog_api_station_id () const {return m_->cloudLogStationID_;}
bool Configuration::prompt_to_log () const {return m_->prompt_to_log_;}
bool Configuration::autoLog() const {return m_->autoLog_;}
bool Configuration::contestingOnly() const {return m_->contestingOnly_;}
bool Configuration::ZZ00() const {return m_->ZZ00_;}
bool Configuration::log4digitGrids() const {return m_->log4digitGrids_;}
bool Configuration::decodes_from_top () const {return m_->decodes_from_top_;}
bool Configuration::insert_blank () const {return m_->insert_blank_;}
bool Configuration::detailed_blank () const {return m_->detailed_blank_;}
bool Configuration::DXCC () const {return m_->DXCC_;}
bool Configuration::GridMap() const { return m_->gridMap_;}
bool Configuration::GridMapAll() const { return m_->gridMapAll_;}
bool Configuration::ppfx() const {return m_->ppfx_;}
bool Configuration::miles () const {return m_->miles_;}
bool Configuration::quick_call () const {return m_->quick_call_;}
bool Configuration::disable_TX_on_73 () const {return m_->disable_TX_on_73_;}
bool Configuration::force_call_1st() const {return m_->force_call_1st_;}
bool Configuration::alternate_bindings() const {return m_->alternate_bindings_;}
int Configuration::watchdog () const {return m_->watchdog_;}
int Configuration::tune_watchdog_time () const {return m_->tune_watchdog_time_;}
bool Configuration::tune_watchdog () const {return m_->tune_watchdog_;}
bool Configuration::TX_messages () const {return m_->TX_messages_;}
bool Configuration::enable_VHF_features () const {return m_->enable_VHF_features_;}
bool Configuration::decode_at_52s () const {return m_->decode_at_52s_;}
bool Configuration::kHz_without_k () const {return m_->kHz_without_k_;}
bool Configuration::button_coloring_disabled () const {return m_->button_coloring_disabled_;}
bool Configuration::Wait_features_enabled () const {return m_->Wait_features_enabled_;}
bool Configuration::showDistance() const {return m_->showDistance_;}
bool Configuration::showAzimuth() const {return m_->showAzimuth_;}
bool Configuration::align() const {return m_->align_;}
bool Configuration::repeat_Tx () const {return m_->repeat_Tx_;}
bool Configuration::auto_astro () const {return m_->auto_astro_;}
bool Configuration::single_decode () const {return m_->single_decode_;}
bool Configuration::twoPass() const {return m_->twoPass_;}
bool Configuration::highDPI() const {return m_->highDPI_;}
bool Configuration::largerTabWidget() const {return m_->largerTabWidget_;}
bool Configuration::superFox() const {return m_->bSuperFox_;}
bool Configuration::Individual_Contest_Name() const {return m_->Individual_Contest_Name_;}
bool Configuration::NCCC_Sprint() const {return m_->NCCC_Sprint_;}
bool Configuration::Blacklisted() const {return m_->Blacklisted_;}
bool Configuration::Whitelisted() const {return m_->Whitelisted_;}
bool Configuration::AlwaysPass() const {return m_->AlwaysPass_;}
bool Configuration::filters_for_Wait_and_Pounce_only() const {return m_->filters_for_Wait_and_Pounce_only_;}
bool Configuration::filters_for_word2() const {return m_->filters_for_word2_;}
bool Configuration::twoDays() const {return m_->twoDays_;}
bool Configuration::PWR_and_SWR () const {return m_->PWR_and_SWR_;}
bool Configuration::check_SWR () const {return m_->check_SWR_;}
bool Configuration::x2ToneSpacing() const {return m_->x2ToneSpacing_;}
bool Configuration::x4ToneSpacing() const {return m_->x4ToneSpacing_;}
bool Configuration::split_mode () const {return m_->split_mode ();}
QString Configuration::opCall() const {return m_->opCall_;}
void Configuration::opCall (QString const& call) {m_->opCall_ = call;}
QString Configuration::udp_server_name () const {return m_->udp_server_name_;}
auto Configuration::udp_server_port () const -> port_type {return m_->udp_server_port_;}
QStringList Configuration::udp_interface_names () const {return m_->udp_interface_names_;}
int Configuration::udp_TTL () const {return m_->udp_TTL_;}
bool Configuration::accept_udp_requests () const {return m_->accept_udp_requests_;}
QString Configuration::n1mm_server_name () const {return m_->n1mm_server_name_;}
auto Configuration::n1mm_server_port () const -> port_type {return m_->n1mm_server_port_;}
bool Configuration::broadcast_to_n1mm () const {return m_->broadcast_to_n1mm_;}
bool Configuration::broadcast_to_cloudlog () const {return m_->bCloudLog_;}
bool Configuration::lowSidelobes() const {return m_->bLowSidelobes_;}
bool Configuration::udpWindowToFront () const {return m_->udpWindowToFront_;}
bool Configuration::udpWindowRestore () const {return m_->udpWindowRestore_;}
Bands * Configuration::bands () {return &m_->bands_;}
Bands const * Configuration::bands () const {return &m_->bands_;}
StationList * Configuration::stations () {return &m_->stations_;}
StationList const * Configuration::stations () const {return &m_->stations_;}
IARURegions::Region Configuration::region () const {return m_->region_;}
FrequencyList_v2_101 * Configuration::frequencies () {return &m_->frequencies_;}
FrequencyList_v2_101 const * Configuration::frequencies () const {return &m_->frequencies_;}
QStringListModel * Configuration::macros () {return &m_->macros_;}
QStringListModel const * Configuration::macros () const {return &m_->macros_;}
QDir Configuration::save_directory () const {return m_->save_directory_;}
QDir Configuration::azel_directory () const {return m_->azel_directory_;}
QString Configuration::rig_name () const {return m_->rig_params_.rig_name;}
bool Configuration::AzElExtraLines () const {return m_->AzElExtraLines_;}
bool Configuration::pwrBandTxMemory () const {return m_->pwrBandTxMemory_;}
bool Configuration::pwrBandTuneMemory () const {return m_->pwrBandTuneMemory_;}
LotWUsers const& Configuration::lotw_users () const {return m_->lotw_users_;}
DecodeHighlightingModel const& Configuration::decode_highlighting () const {return m_->decode_highlighing_model_;}
bool Configuration::highlight_by_mode () const {return m_->highlight_by_mode_;}
bool Configuration::highlight_only_fields () const {return m_->highlight_only_fields_;}
bool Configuration::include_WAE_entities () const {return m_->include_WAE_entities_;}
bool Configuration::highlight_73 () const {return m_->highlight_73_;}
bool Configuration::highlight_orange () const {return m_->highlight_orange_;}
bool Configuration::highlight_blue () const {return m_->highlight_blue_;}
bool Configuration::bSpecialOp () const {return m_->bSpecialOp_;}
bool Configuration::alternate_erase_button () const {return m_->alternate_erase_button_;}
bool Configuration::show_country_names () const {return m_->show_country_names_;}
bool Configuration::highlight_DXcall () const {return m_->highlight_DXcall_;}
bool Configuration::clear_DXcall () const {return m_->clear_DXcall_;}
bool Configuration::highlight_DXgrid () const {return m_->highlight_DXgrid_;}
bool Configuration::clear_DXgrid () const {return m_->clear_DXgrid_;}
bool Configuration::erase_BandActivity () const {return m_->erase_BandActivity_;}
bool Configuration::set_RXtoTX () const {return m_->set_RXtoTX_;}
bool Configuration::alert_CQ () const {return m_->alert_CQ_;}
bool Configuration::alert_MyCall () const {return m_->alert_MyCall_;}
bool Configuration::alert_DXCC () const {return m_->alert_DXCC_;}
bool Configuration::alert_DXCCOB () const {return m_->alert_DXCCOB_;}
bool Configuration::alert_Grid () const {return m_->alert_Grid_;}
bool Configuration::alert_GridOB () const {return m_->alert_GridOB_;}
bool Configuration::alert_Continent () const {return m_->alert_Continent_;}
bool Configuration::alert_ContinentOB () const {return m_->alert_ContinentOB_;}
bool Configuration::alert_CQZ () const {return m_->alert_CQZ_;}
bool Configuration::alert_CQZOB () const {return m_->alert_CQZOB_;}
bool Configuration::alert_ITUZ () const {return m_->alert_ITUZ_;}
bool Configuration::alert_ITUZOB () const {return m_->alert_ITUZOB_;}
bool Configuration::alert_DXcall () const {return m_->alert_DXcall_;}
bool Configuration::alert_QSYmessage () const {return m_->alert_QSYmessage_;}
bool Configuration::alert_Enabled () const {return m_->alert_Enabled_;}


void Configuration::set_CTY_DAT_version(QString const& version)
{
  m_->set_CTY_DAT_version(version);
}

void Configuration::read_CALL3_version ()
{
  m_->read_CALL3_version ();
}

void Configuration::set_calibration (CalibrationParams params)
{
  m_->calibration_ = params;
}

void Configuration::enable_calibration (bool on)
{
  auto target_frequency = m_->remove_calibration (m_->cached_rig_state_.frequency ()) - m_->current_offset_;
  m_->frequency_calibration_disabled_ = !on;
  transceiver_frequency (target_frequency);
}

bool Configuration::is_transceiver_online () const
{
  return m_->rig_active_;
}

bool Configuration::is_dummy_rig () const
{
  return m_->rig_is_dummy_;
}

bool Configuration::is_tci () const
{
  return m_->is_tci_;
}

bool Configuration::transceiver_online ()
{
  LOG_TRACE (m_->cached_rig_state_);
  return m_->have_rig ();
}

int Configuration::transceiver_resolution () const
{
  return m_->rig_resolution_;
}

void Configuration::transceiver_offline ()
{
  LOG_TRACE (m_->cached_rig_state_);
  m_->close_rig ();
}

void Configuration::transceiver_frequency (Frequency f)
{
  LOG_TRACE (f << ' ' << m_->cached_rig_state_);
  m_->transceiver_frequency (f);
}

void Configuration::transceiver_tx_frequency (Frequency f)
{
  LOG_TRACE (f << ' ' << m_->cached_rig_state_);
  m_->transceiver_tx_frequency (f);
}

void Configuration::transceiver_mode (MODE mode)
{
  LOG_TRACE (mode << ' ' << m_->cached_rig_state_);
  m_->transceiver_mode (mode);
}

void Configuration::transceiver_ptt (bool on)
{
  LOG_TRACE (on << ' ' << m_->cached_rig_state_);
  m_->transceiver_ptt (on);
}

void Configuration::transceiver_audio (bool on)
{
  LOG_TRACE (on << ' ' << m_->cached_rig_state_);
  m_->transceiver_audio (on);
}

void Configuration::transceiver_tune (bool on)
{
  LOG_TRACE (on << ' ' << m_->cached_rig_state_);
  m_->transceiver_tune (on);
}

void Configuration::transceiver_period (double period)
{
#if WSJT_TRACE_CAT
  qDebug () << "Configuration::transceiver_period:" << period << m_->cached_rig_state_;
#endif

  m_->transceiver_period (period);
}

void Configuration::transceiver_blocksize (qint32 blocksize)
{
#if WSJT_TRACE_CAT
  qDebug () << "Configuration::transceiver_blocksize:" << blocksize << m_->cached_rig_state_;
#endif

  m_->transceiver_blocksize (blocksize);
}

void Configuration::transceiver_modulator_start(QString jtmode, unsigned symbolslength, double framespersymbol, double trfrequency,
                     double tonespacing, bool synchronize, bool fastmode, double dbsnr, double trperiod)
{
#if WSJT_TRACE_CAT
  qDebug () << "Configuration::transceiver_modulator_start:" << symbolslength << m_->cached_rig_state_;
#endif

  m_->transceiver_modulator_start(jtmode, symbolslength,framespersymbol,trfrequency,tonespacing,synchronize,fastmode,dbsnr,trperiod);
}

void Configuration::transceiver_modulator_stop (bool on)
{
#if WSJT_TRACE_CAT
  qDebug () << "Configuration::transceiver_stop:" << on << m_->cached_rig_state_;
#endif

  m_->transceiver_modulator_stop (on);
}

void Configuration::transceiver_spread (double spread)
{
#if WSJT_TRACE_CAT
  qDebug () << "Configuration::transceiver_spread:" << spread << m_->cached_rig_state_;
#endif

  m_->transceiver_spread (spread);
}

void Configuration::transceiver_nsym (qint32 nsym)
{
#if WSJT_TRACE_CAT
  qDebug () << "Configuration::transceiver_nsym:" << nsym << m_->cached_rig_state_;
#endif

  m_->transceiver_nsym (nsym);
}

void Configuration::transceiver_trfrequency (double trfrequency)
{
#if WSJT_TRACE_CAT
  qDebug () << "Configuration::transceiver_trfrequency:" << trfrequency << m_->cached_rig_state_;
#endif

  m_->transceiver_trfrequency (trfrequency);
}

void Configuration::transceiver_txvolume (qreal txvolume)
{
#if WSJT_TRACE_CAT
  qDebug () << "Configuration::transceiver_txvolume:" << txvolume << m_->cached_rig_state_;
#endif

  m_->transceiver_txvolume (txvolume);
}

void Configuration::transceiver_volume (qreal volume)
{
#if WSJT_TRACE_CAT
  qDebug () << "Configuration::transceiver_volume:" << volume << m_->cached_rig_state_;
#endif

  m_->transceiver_volume (volume);
}


void Configuration::sync_transceiver (bool force_signal, bool enforce_mode_and_split)
{
  LOG_TRACE ("force signal: " << force_signal << " enforce_mode_and_split: " << enforce_mode_and_split << ' ' << m_->cached_rig_state_);
  m_->sync_transceiver (force_signal);
  if (!enforce_mode_and_split)
    {
      m_->transceiver_tx_frequency (0);
    }
}

void Configuration::invalidate_audio_input_device (QString /* error */)
{
  m_->audio_input_device_ = QAudioDeviceInfo {};
}

void Configuration::invalidate_audio_output_device (QString /* error */)
{
  m_->audio_output_device_ = QAudioDeviceInfo {};
}

// OTP seed can be empty, in which case it is not used, or a valid 16 character base32 string.
bool Configuration::validate_otp_seed(QString seed)
{
  if (seed.isEmpty())
    {
      return true;
    }
  if (seed.size() != 16)
    {
      return false;
    }
  for (QChar c: seed)
  {
    if (!QString(BASE32_CHARSET).contains(c))
    {
      return false;
    }
  }
  return true;
}
bool Configuration::valid_n1mm_info () const
{
  // do very rudimentary checking on the n1mm server name and port number.
  //
  auto server_name = m_->n1mm_server_name_;
  auto port_number = m_->n1mm_server_port_;
  return(!(server_name.trimmed().isEmpty() || port_number == 0));
}

QString Configuration::my_grid() const
{
  auto the_grid = m_->my_grid_;
  if (m_->use_dynamic_grid_ && m_->dynamic_grid_.size () >= 4) {
    the_grid = m_->dynamic_grid_;
  }
  return the_grid;
}

QString Configuration::Field_Day_Exchange() const
{
  return m_->FD_exchange_;
}

QString Configuration::RTTY_Exchange() const
{
  return m_->RTTY_exchange_;
}

QString Configuration::Contest_Name() const
{
  return m_->Contest_Name_;
}

QString Configuration::Blacklist1() const
{
  return m_->Blacklist1_;
}

QString Configuration::Blacklist2() const
{
  return m_->Blacklist2_;
}

QString Configuration::Blacklist3() const
{
  return m_->Blacklist3_;
}

QString Configuration::Blacklist4() const
{
  return m_->Blacklist4_;
}

QString Configuration::Blacklist5() const
{
  return m_->Blacklist5_;
}

QString Configuration::Blacklist6() const
{
  return m_->Blacklist6_;
}

QString Configuration::Blacklist7() const
{
  return m_->Blacklist7_;
}

QString Configuration::Blacklist8() const
{
  return m_->Blacklist8_;
}

QString Configuration::Blacklist9() const
{
  return m_->Blacklist9_;
}

QString Configuration::Blacklist10() const
{
  return m_->Blacklist10_;
}

QString Configuration::Blacklist11() const
{
  return m_->Blacklist11_;
}

QString Configuration::Blacklist12() const
{
  return m_->Blacklist12_;
}

QString Configuration::Whitelist1() const
{
  return m_->Whitelist1_;
}

QString Configuration::Whitelist2() const
{
  return m_->Whitelist2_;
}

QString Configuration::Whitelist3() const
{
  return m_->Whitelist3_;
}

QString Configuration::Whitelist4() const
{
  return m_->Whitelist4_;
}

QString Configuration::Whitelist5() const
{
  return m_->Whitelist5_;
}

QString Configuration::Whitelist6() const
{
  return m_->Whitelist6_;
}

QString Configuration::Whitelist7() const
{
  return m_->Whitelist7_;
}

QString Configuration::Whitelist8() const
{
  return m_->Whitelist8_;
}

QString Configuration::Whitelist9() const
{
  return m_->Whitelist9_;
}

QString Configuration::Whitelist10() const
{
  return m_->Whitelist10_;
}

QString Configuration::Whitelist11() const
{
  return m_->Whitelist11_;
}

QString Configuration::Whitelist12() const
{
  return m_->Whitelist12_;
}

QString Configuration::Pass1() const
{
  return m_->Pass1_;
}

QString Configuration::Pass2() const
{
  return m_->Pass2_;
}

QString Configuration::Pass3() const
{
  return m_->Pass3_;
}

QString Configuration::Pass4() const
{
  return m_->Pass4_;
}

QString Configuration::Pass5() const
{
  return m_->Pass5_;
}

QString Configuration::Pass6() const
{
  return m_->Pass6_;
}

QString Configuration::Pass7() const
{
  return m_->Pass7_;
}

QString Configuration::Pass8() const
{
  return m_->Pass8_;
}

QString Configuration::Pass9() const
{
  return m_->Pass9_;
}

QString Configuration::Pass10() const
{
  return m_->Pass10_;
}

QString Configuration::Pass11() const
{
  return m_->Pass11_;
}

QString Configuration::Pass12() const
{
  return m_->Pass12_;
}

QString Configuration::Territory1() const
{
  return m_->Territory1_;
}

QString Configuration::Territory2() const
{
  return m_->Territory2_;
}

QString Configuration::Territory3() const
{
  return m_->Territory3_;
}

QString Configuration::Territory4() const
{
  return m_->Territory4_;
}

QString Configuration::highlight_orange_callsigns() const
{
  return m_->highlight_orange_callsigns_;
}

QString Configuration::highlight_blue_callsigns() const
{
  return m_->highlight_blue_callsigns_;
}

auto Configuration::special_op_id () const -> SpecialOperatingActivity
{
  return m_->bSpecialOp_ ? static_cast<SpecialOperatingActivity> (m_->SelectedActivity_) : SpecialOperatingActivity::NONE;
}

void Configuration::set_location (QString const& grid_descriptor)
{
  // change the dynamic grid
  // qDebug () << "Configuration::set_location - location:" << grid_descriptor;
  m_->dynamic_grid_ = grid_descriptor.trimmed ();
}

void Configuration::setSpecial_Q65_Pileup()
{
  m_->bSpecialOp_=true;
  m_->ui_->gbSpecialOpActivity->setChecked(m_->bSpecialOp_);
  m_->ui_->rbQ65pileup->setChecked(true);
  m_->SelectedActivity_ = static_cast<int> (SpecialOperatingActivity::Q65_PILEUP);
  m_->write_settings();
}

void Configuration::setSpecial_Hound()
{
  m_->bSpecialOp_=true;
  m_->ui_->gbSpecialOpActivity->setChecked(m_->bSpecialOp_);
  m_->ui_->rbHound->setChecked(true);
  m_->SelectedActivity_ = static_cast<int> (SpecialOperatingActivity::HOUND);
  m_->write_settings();
}

void Configuration::setSpecial_Fox()
{
  m_->bSpecialOp_=true;
  m_->ui_->gbSpecialOpActivity->setChecked(m_->bSpecialOp_);
  m_->ui_->rbFox->setChecked(true);
  m_->SelectedActivity_ = static_cast<int> (SpecialOperatingActivity::FOX);
  m_->write_settings();
}

void Configuration::setSpecial_None()
{
  m_->bSpecialOp_=false;
  m_->ui_->gbSpecialOpActivity->setChecked(m_->bSpecialOp_);
  m_->write_settings();
}

void Configuration::setSpecial_On()
{
  m_->bSpecialOp_=true;
  m_->ui_->gbSpecialOpActivity->setChecked(m_->bSpecialOp_);
  m_->write_settings();
}

void Configuration::toggle_SF()
{
  if (m_->bSuperFox_) {
    m_->ui_->cbSuperFox->setChecked(false);
  } else {
    m_->ui_->cbSuperFox->setChecked(true);
  }
  m_->bSuperFox_ = m_->ui_->cbSuperFox->isChecked ();
  m_->write_settings();
}

QString Configuration::OTPSeed() const
{
  return m_->OTPSeed_;
}

QString Configuration::OTPUrl() const
{
  return m_->OTPUrl_;
}

unsigned int Configuration::OTPinterval() const
{
  return m_->OTPinterval_;
}

bool Configuration::OTPEnabled() const
{
  return m_->OTPSeed_.size() == 16 && m_->OTPEnabled_;
}

bool Configuration::ShowOTP () const
{
  return m_->ShowOTP_;
}

namespace
{
#if defined (Q_OS_MAC)
  char const * app_root = "/../../../";
#else
  char const * app_root = "/../";
#endif
  QString doc_path ()
  {
#if CMAKE_BUILD
    if (QDir::isRelativePath (CMAKE_INSTALL_DOCDIR))
      {
	return QApplication::applicationDirPath () + app_root + CMAKE_INSTALL_DOCDIR;
      }
    return CMAKE_INSTALL_DOCDIR;
#else
    return QApplication::applicationDirPath ();
#endif
  }

  QString data_path ()
  {
#if CMAKE_BUILD
    if (QDir::isRelativePath (CMAKE_INSTALL_DATADIR))
      {
	return QApplication::applicationDirPath () + app_root + CMAKE_INSTALL_DATADIR + QChar {'/'} + CMAKE_PROJECT_NAME;
      }
    return CMAKE_INSTALL_DATADIR;
#else
    return QApplication::applicationDirPath ();
#endif
  }
}

Configuration::impl::impl (Configuration * self, QNetworkAccessManager * network_manager
                           , QDir const& temp_directory, QSettings * settings, LogBook * logbook
                           , QWidget * parent)
  : QDialog {parent}
  , self_ {self}
  , transceiver_thread_ {nullptr}
  , ui_ {new Ui::configuration_dialog}
  , network_manager_ {network_manager}
  , settings_ {settings}
  , logbook_ {logbook}
  , doc_dir_ {doc_path ()}
  , data_dir_ {data_path ()}
  , temp_dir_ {temp_directory}
  , writeable_data_dir_ {QStandardPaths::writableLocation (QStandardPaths::DataLocation)}
  , lotw_users_ {network_manager_}
  , cloudlog_ {self, network_manager_}
  , restart_sound_input_device_ {false}
  , restart_sound_output_device_ {false}
  , restart_tci_device_ {false}
  , frequencies_ {&bands_}
  , next_frequencies_ {&bands_}
  , stations_ {&bands_}
  , next_stations_ {&bands_}
  , current_offset_ {0}
  , current_tx_offset_ {0}
  , frequency_dialog_ {new FrequencyDialog {&regions_, &modes_, this}}
  , station_delete_action_ {tr ("&Delete"), nullptr}
  , station_insert_action_ {tr ("&Insert ..."), nullptr}
  , station_dialog_ {new StationDialog {&next_stations_, &bands_, this}}
  , highlight_by_mode_ {false}
  , highlight_only_fields_ {false}
  , include_WAE_entities_ {false}
  , highlight_73_ {false}
  , highlight_orange_ {false}
  , highlight_blue_ {false}
  , bSpecialOp_ {false}
  , alternate_erase_button_ {false}
  , show_country_names_ {false}
  , LotW_days_since_upload_ {0}
  , last_port_type_ {TransceiverFactory::Capabilities::none}
  , rig_is_dummy_ {false}
  , is_tci_ {false}
  , rig_active_ {false}
  , have_rig_ {false}
  , rig_changed_ {false}
  , rig_resolution_ {0}
  , frequency_calibration_disabled_ {false}
  , transceiver_command_number_ {0}
  , degrade_ {0.}               // initialize to zero each run, not
                                // saved in settings
  , udp_server_name_edited_ {false}
  , dns_lookup_id_ {-1}
  , default_audio_input_device_selected_ {false}
  , default_audio_output_device_selected_ {false}
{
  ui_->setupUi (this);

  {
    // Make sure the default save directory exists
    QString save_dir {"save"};
    default_save_directory_ = writeable_data_dir_;
    default_azel_directory_ = writeable_data_dir_;
    if (!default_save_directory_.mkpath (save_dir) || !default_save_directory_.cd (save_dir))
      {
        MessageBox::critical_message (this, tr ("Failed to create save directory"),
                                      tr ("path: \"%1\%")
                                      .arg (default_save_directory_.absoluteFilePath (save_dir)));
        throw std::runtime_error {"Failed to create save directory"};
      }

    // we now have a deafult save path that exists

    // make sure samples directory exists
    QString samples_dir {"samples"};
    if (!default_save_directory_.mkpath (samples_dir))
      {
        MessageBox::critical_message (this, tr ("Failed to create samples directory"),
                                      tr ("path: \"%1\"")
                                      .arg (default_save_directory_.absoluteFilePath (samples_dir)));
        throw std::runtime_error {"Failed to create samples directory"};
      }

    // copy in any new sample files to the sample directory
    QDir dest_dir {default_save_directory_};
    dest_dir.cd (samples_dir);
    
    QDir source_dir {":/" + samples_dir};
    source_dir.cd (save_dir);
    source_dir.cd (samples_dir);
    auto list = source_dir.entryInfoList (QStringList {{"*.wav"}}, QDir::Files | QDir::Readable);
    Q_FOREACH (auto const& item, list)
      {
        if (!dest_dir.exists (item.fileName ()))
          {
            QFile file {item.absoluteFilePath ()};
            file.copy (dest_dir.absoluteFilePath (item.fileName ()));
          }
      }
  }

  // this must be done after the default paths above are set
  read_settings ();

  // set up dynamic loading of audio devices
  connect (ui_->sound_input_combo_box, &LazyFillComboBox::about_to_show_popup, [this] () {
      QGuiApplication::setOverrideCursor (QCursor {Qt::WaitCursor});
      load_audio_devices (QAudio::AudioInput, ui_->sound_input_combo_box, &next_audio_input_device_);
      update_audio_channels (ui_->sound_input_combo_box, ui_->sound_input_combo_box->currentIndex (), ui_->sound_input_channel_combo_box, false);
      ui_->sound_input_channel_combo_box->setCurrentIndex (next_audio_input_channel_);
      QGuiApplication::restoreOverrideCursor ();
    });
  connect (ui_->sound_output_combo_box, &LazyFillComboBox::about_to_show_popup, [this] () {
      QGuiApplication::setOverrideCursor (QCursor {Qt::WaitCursor});
      load_audio_devices (QAudio::AudioOutput, ui_->sound_output_combo_box, &next_audio_output_device_);
      update_audio_channels (ui_->sound_output_combo_box, ui_->sound_output_combo_box->currentIndex (), ui_->sound_output_channel_combo_box, true);
      ui_->sound_output_channel_combo_box->setCurrentIndex (next_audio_output_channel_);
      QGuiApplication::restoreOverrideCursor ();
    });

  // set up dynamic loading of network interfaces
  connect (ui_->udp_interfaces_combo_box, &LazyFillComboBox::about_to_show_popup, [this] () {
      QGuiApplication::setOverrideCursor (QCursor {Qt::WaitCursor});
      load_network_interfaces (ui_->udp_interfaces_combo_box, udp_interface_names_);
      QGuiApplication::restoreOverrideCursor ();
    });
  connect (ui_->udp_interfaces_combo_box, &QComboBox::currentTextChanged, this, &Configuration::impl::validate_network_interfaces);

  // set up LoTW users CSV file fetching
  connect (&lotw_users_, &LotWUsers::load_finished, [this] () {
    ui_->LotW_CSV_fetch_push_button->setEnabled (true);
  });

  connect(&lotw_users_, &LotWUsers::progress, [this] (QString const& msg) {
      ui_->LotW_CSV_status_label->setText(msg);
  });

  lotw_users_.set_local_file_path (writeable_data_dir_.absoluteFilePath ("lotw-user-activity.csv"));

  // set up Cloudlog API key test button
  connect (&cloudlog_, &Cloudlog::apikey_ok, [this] () {
      ui_->pbTestCloudlog->setStyleSheet ("QPushButton {background-color: green;}");
      ui_->pbTestCloudlog->setToolTip (tr ("API key OK"));
    });
  connect (&cloudlog_, &Cloudlog::apikey_ro, [this] () {
      ui_->pbTestCloudlog->setStyleSheet ("QPushButton {background-color: orange;}");
      ui_->pbTestCloudlog->setToolTip (tr ("API key read-only"));
    });
  connect (&cloudlog_, &Cloudlog::apikey_invalid, [this] () {
      ui_->pbTestCloudlog->setStyleSheet ("QPushButton {background-color: red;}");
      ui_->pbTestCloudlog->setToolTip (tr ("API key invalid"));
    });

  //
  // validation
  //
  ui_->callsign_line_edit->setValidator (new CallsignValidator {this});
  ui_->grid_line_edit->setValidator (new MaidenheadLocatorValidator {this});
  ui_->add_macro_line_edit->setValidator (new QRegularExpressionValidator {message_alphabet, this});
  ui_->Field_Day_Exchange->setValidator (new QRegularExpressionValidator {field_day_exchange_re, this});
  ui_->RTTY_Exchange->setValidator (new QRegularExpressionValidator {RTTY_roundup_exchange_re, this});
  QRegularExpression b32(QString("(^[") + QString(BASE32_CHARSET)+QString(BASE32_CHARSET).toLower() + QString("]{16}$)|(^$)"));
  ui_->OTPSeed->setValidator(new QRegularExpressionValidator(b32, this));

  //
  // assign ids to radio buttons
  //
  ui_->CAT_data_bits_button_group->setId (ui_->CAT_default_bit_radio_button, TransceiverFactory::default_data_bits);
  ui_->CAT_data_bits_button_group->setId (ui_->CAT_7_bit_radio_button, TransceiverFactory::seven_data_bits);
  ui_->CAT_data_bits_button_group->setId (ui_->CAT_8_bit_radio_button, TransceiverFactory::eight_data_bits);

  ui_->CAT_stop_bits_button_group->setId (ui_->CAT_default_stop_bit_radio_button, TransceiverFactory::default_stop_bits);
  ui_->CAT_stop_bits_button_group->setId (ui_->CAT_one_stop_bit_radio_button, TransceiverFactory::one_stop_bit);
  ui_->CAT_stop_bits_button_group->setId (ui_->CAT_two_stop_bit_radio_button, TransceiverFactory::two_stop_bits);

  ui_->CAT_handshake_button_group->setId (ui_->CAT_handshake_default_radio_button, TransceiverFactory::handshake_default);
  ui_->CAT_handshake_button_group->setId (ui_->CAT_handshake_none_radio_button, TransceiverFactory::handshake_none);
  ui_->CAT_handshake_button_group->setId (ui_->CAT_handshake_xon_radio_button, TransceiverFactory::handshake_XonXoff);
  ui_->CAT_handshake_button_group->setId (ui_->CAT_handshake_hardware_radio_button, TransceiverFactory::handshake_hardware);

  ui_->PTT_method_button_group->setId (ui_->PTT_VOX_radio_button, TransceiverFactory::PTT_method_VOX);
  ui_->PTT_method_button_group->setId (ui_->PTT_CAT_radio_button, TransceiverFactory::PTT_method_CAT);
  ui_->PTT_method_button_group->setId (ui_->PTT_DTR_radio_button, TransceiverFactory::PTT_method_DTR);
  ui_->PTT_method_button_group->setId (ui_->PTT_RTS_radio_button, TransceiverFactory::PTT_method_RTS);

  ui_->TX_audio_source_button_group->setId (ui_->TX_source_mic_radio_button, TransceiverFactory::TX_audio_source_front);
  ui_->TX_audio_source_button_group->setId (ui_->TX_source_data_radio_button, TransceiverFactory::TX_audio_source_rear);

  ui_->TX_mode_button_group->setId (ui_->mode_none_radio_button, data_mode_none);
  ui_->TX_mode_button_group->setId (ui_->mode_USB_radio_button, data_mode_USB);
  ui_->TX_mode_button_group->setId (ui_->mode_data_radio_button, data_mode_data);

  ui_->split_mode_button_group->setId (ui_->split_none_radio_button, TransceiverFactory::split_mode_none);
  ui_->split_mode_button_group->setId (ui_->split_rig_radio_button, TransceiverFactory::split_mode_rig);
  ui_->split_mode_button_group->setId (ui_->split_emulate_radio_button, TransceiverFactory::split_mode_emulate);

  ui_->special_op_activity_button_group->setId (ui_->rbNA_VHF_Contest, static_cast<int> (SpecialOperatingActivity::NA_VHF));
  ui_->special_op_activity_button_group->setId (ui_->rbEU_VHF_Contest, static_cast<int> (SpecialOperatingActivity::EU_VHF));
  ui_->special_op_activity_button_group->setId (ui_->rbField_Day, static_cast<int> (SpecialOperatingActivity::FIELD_DAY));
  ui_->special_op_activity_button_group->setId (ui_->rbRTTY_Roundup, static_cast<int> (SpecialOperatingActivity::RTTY));
  ui_->special_op_activity_button_group->setId (ui_->rbWW_DIGI, static_cast<int> (SpecialOperatingActivity::WW_DIGI));
  ui_->special_op_activity_button_group->setId (ui_->rbARRL_Digi, static_cast<int> (SpecialOperatingActivity::ARRL_DIGI));
  ui_->special_op_activity_button_group->setId (ui_->rbFox, static_cast<int> (SpecialOperatingActivity::FOX));
  ui_->special_op_activity_button_group->setId (ui_->rbHound, static_cast<int> (SpecialOperatingActivity::HOUND));
  ui_->special_op_activity_button_group->setId (ui_->rbQ65pileup, static_cast<int> (SpecialOperatingActivity::Q65_PILEUP));

  //
  // setup PTT port combo box drop down content
  //
  fill_port_combo_box (ui_->PTT_port_combo_box);
  ui_->PTT_port_combo_box->addItem ("CAT");
  ui_->PTT_port_combo_box->setItemData (ui_->PTT_port_combo_box->count () - 1, "Delegate to proxy CAT service", Qt::ToolTipRole);

  //
  // setup hooks to keep audio channels aligned with devices
  //
  {
    using namespace std;
    using namespace std::placeholders;

    function<void (int)> cb (bind (&Configuration::impl::update_audio_channels, this, ui_->sound_input_combo_box, _1, ui_->sound_input_channel_combo_box, false));
    connect (ui_->sound_input_combo_box, static_cast<void (QComboBox::*)(int)> (&QComboBox::currentIndexChanged), cb);
    cb = bind (&Configuration::impl::update_audio_channels, this, ui_->sound_output_combo_box, _1, ui_->sound_output_channel_combo_box, true);
    connect (ui_->sound_output_combo_box, static_cast<void (QComboBox::*)(int)> (&QComboBox::currentIndexChanged), cb);
  }

  //
  // setup macros list view
  //
  ui_->macros_list_view->setModel (&next_macros_);
  ui_->macros_list_view->setItemDelegate (new MessageItemDelegate {this});

  macro_delete_action_ = new QAction {tr ("&Delete"), ui_->macros_list_view};
  ui_->macros_list_view->insertAction (nullptr, macro_delete_action_);
  connect (macro_delete_action_, &QAction::triggered, this, &Configuration::impl::delete_macro);

  // setup IARU region combo box model
  ui_->region_combo_box->setModel (&regions_);

  //
  // setup working frequencies table model & view
  //
  frequencies_.sort (FrequencyList_v2_101::frequency_column);

  ui_->frequencies_table_view->setModel (&next_frequencies_);
  ui_->frequencies_table_view->horizontalHeader ()->setSectionResizeMode (QHeaderView::ResizeToContents);

  ui_->frequencies_table_view->horizontalHeader ()->setResizeContentsPrecision (0);
  ui_->frequencies_table_view->horizontalHeader ()->moveSection(8, 3); // swap preferred to be in front of description
  ui_->frequencies_table_view->verticalHeader ()->setSectionResizeMode (QHeaderView::ResizeToContents);
  ui_->frequencies_table_view->verticalHeader ()->setResizeContentsPrecision (0);
  ui_->frequencies_table_view->sortByColumn (FrequencyList_v2_101::frequency_column, Qt::AscendingOrder);
  ui_->frequencies_table_view->setColumnHidden (FrequencyList_v2_101::frequency_mhz_column, true);
  ui_->frequencies_table_view->setColumnHidden (FrequencyList_v2_101::source_column, true);

  // delegates
  ui_->frequencies_table_view->setItemDelegateForColumn (FrequencyList_v2_101::frequency_column, new FrequencyDelegate {this});
  ui_->frequencies_table_view->setItemDelegateForColumn (FrequencyList_v2_101::region_column, new ForeignKeyDelegate {&regions_, 0, this});
  ui_->frequencies_table_view->setItemDelegateForColumn (FrequencyList_v2_101::mode_column, new ForeignKeyDelegate {&modes_, 0, this});

  // actions
  frequency_delete_action_ = new QAction {tr ("&Delete"), ui_->frequencies_table_view};
  ui_->frequencies_table_view->insertAction (nullptr, frequency_delete_action_);
  connect (frequency_delete_action_, &QAction::triggered, this, &Configuration::impl::delete_frequencies);

  frequency_insert_action_ = new QAction {tr ("&Insert ..."), ui_->frequencies_table_view};
  ui_->frequencies_table_view->insertAction (nullptr, frequency_insert_action_);
  connect (frequency_insert_action_, &QAction::triggered, this, &Configuration::impl::insert_frequency);

  load_frequencies_action_ = new QAction {tr ("&Load ..."), ui_->frequencies_table_view};
  ui_->frequencies_table_view->insertAction (nullptr, load_frequencies_action_);
  connect (load_frequencies_action_, &QAction::triggered, this, &Configuration::impl::load_frequencies);

  save_frequencies_action_ = new QAction {tr ("&Save as ..."), ui_->frequencies_table_view};
  ui_->frequencies_table_view->insertAction (nullptr, save_frequencies_action_);
  connect (save_frequencies_action_, &QAction::triggered, this, &Configuration::impl::save_frequencies);

  merge_frequencies_action_ = new QAction {tr ("&Merge ..."), ui_->frequencies_table_view};
  ui_->frequencies_table_view->insertAction (nullptr, merge_frequencies_action_);
  connect (merge_frequencies_action_, &QAction::triggered, this, &Configuration::impl::merge_frequencies);

  reset_frequencies_action_ = new QAction {tr ("&Reset"), ui_->frequencies_table_view};
  ui_->frequencies_table_view->insertAction (nullptr, reset_frequencies_action_);
  connect (reset_frequencies_action_, &QAction::triggered, this, &Configuration::impl::reset_frequencies);

  //
  // setup stations table model & view
  //
  stations_.sort (StationList::band_column);
  ui_->stations_table_view->setModel (&next_stations_);
  ui_->stations_table_view->horizontalHeader ()->setSectionResizeMode (QHeaderView::ResizeToContents);
  ui_->stations_table_view->horizontalHeader ()->setResizeContentsPrecision (0);
  ui_->stations_table_view->verticalHeader ()->setSectionResizeMode (QHeaderView::ResizeToContents);
  ui_->stations_table_view->verticalHeader ()->setResizeContentsPrecision (0);
  ui_->stations_table_view->sortByColumn (StationList::band_column, Qt::AscendingOrder);

  // stations delegates
  ui_->stations_table_view->setItemDelegateForColumn (StationList::offset_column, new FrequencyDeltaDelegate {this});
  ui_->stations_table_view->setItemDelegateForColumn (StationList::band_column, new ForeignKeyDelegate {&bands_, &next_stations_, 0, StationList::band_column, this});

  // stations actions
  ui_->stations_table_view->addAction (&station_delete_action_);
  connect (&station_delete_action_, &QAction::triggered, this, &Configuration::impl::delete_stations);

  ui_->stations_table_view->addAction (&station_insert_action_);
  connect (&station_insert_action_, &QAction::triggered, this, &Configuration::impl::insert_station);

  //
  // colours and highlighting setup
  //
  ui_->highlighting_list_view->setModel (&next_decode_highlighing_model_);

  enumerate_rigs ();
  initialize_models ();
  restart_tci_device_ = false;

  audio_input_device_ = next_audio_input_device_;
  audio_input_channel_ = next_audio_input_channel_;
  audio_output_device_ = next_audio_output_device_;
  audio_output_channel_ = next_audio_output_channel_;

  bool fetch_if_needed {false};
  for (auto const& item : decode_highlighing_model_.items ())
    {
      if (DecodeHighlightingModel::Highlight::LotW == item.type_)
        {
          fetch_if_needed = item.enabled_;
          break;
        }
    }
  // load the LoTW users dictionary if it exists, fetch and load if it
  // doesn't and we need it
  lotw_users_.load (ui_->LotW_CSV_URL_line_edit->text (), fetch_if_needed);

  transceiver_thread_ = new QThread {this};
  transceiver_thread_->start ();
}

Configuration::impl::~impl ()
{
  transceiver_thread_->quit ();
  transceiver_thread_->wait ();
  write_settings ();
}

void Configuration::impl::initialize_models ()
{
  next_audio_input_device_ = audio_input_device_;
  next_audio_input_channel_ = audio_input_channel_;
  next_audio_output_device_ = audio_output_device_;
  next_audio_output_channel_ = audio_output_channel_;
  restart_sound_input_device_ = false;
  restart_sound_output_device_ = false;
  restart_tci_device_ = false;

  {
    SettingsGroup g {settings_, "Configuration"};
    find_audio_devices ();
  }
  auto pal = ui_->callsign_line_edit->palette ();
  if (my_callsign_.isEmpty ())
    {
      pal.setColor (QPalette::Base, "#ffccff");
    }
  else
    {
      pal.setColor (QPalette::Base, Qt::white);
    }
  ui_->callsign_line_edit->setPalette (pal);
  ui_->grid_line_edit->setPalette (pal);
  ui_->callsign_line_edit->setText (my_callsign_);
  ui_->grid_line_edit->setText (my_grid_);
  ui_->use_dynamic_grid->setChecked(use_dynamic_grid_);
  ui_->CW_id_interval_spin_box->setValue (id_interval_);
  ui_->align_spin_box->setValue (align_steps_);
  ui_->align_spin_box2->setValue (align_steps2_);
  ui_->sbNtrials->setValue (ntrials_);
  ui_->TCI_spin_box->setValue (volume_);
  ui_->sbTxDelay->setValue (txDelay_);
  ui_->sbAggressive->setValue (aggressive_);
  ui_->sbDegrade->setValue (degrade_);
  ui_->sbBandwidth->setValue (RxBandwidth_);
  ui_->tci_audio_check_box->setChecked (tci_audio_);
  ui_->PTT_method_button_group->button (rig_params_.ptt_type)->setChecked (true);
  ui_->PWR_and_SWR_check_box->setChecked (PWR_and_SWR_);
  ui_->check_SWR_check_box->setChecked (check_SWR_);
  if (!ui_->PWR_and_SWR_check_box->isChecked()) ui_->check_SWR_check_box->setEnabled (false);
  ui_->save_path_display_label->setText (save_directory_.absolutePath ());
  ui_->azel_path_display_label->setText (azel_directory_.absolutePath ());
  ui_->CW_id_after_73_check_box->setChecked (id_after_73_);
  ui_->tx_QSY_check_box->setChecked (tx_QSY_allowed_);
  ui_->progress_bar_check_box->setChecked (progressBar_red_);
  ui_->psk_reporter_check_box->setChecked (spot_to_psk_reporter_);
  ui_->psk_reporter_tcpip_check_box->setChecked (psk_reporter_tcpip_);
  ui_->monitor_off_check_box->setChecked (monitor_off_at_startup_);
  ui_->monitor_last_used_check_box->setChecked (monitor_last_used_);
  ui_->log_as_RTTY_check_box->setChecked (log_as_RTTY_);
  ui_->report_in_comments_check_box->setChecked (report_in_comments_);
  ui_->specOp_in_comments_check_box->setChecked (specOp_in_comments_);
  ui_->prompt_to_log_check_box->setChecked (prompt_to_log_);
  ui_->cbAutoLog->setChecked(autoLog_);
  ui_->cbContestingOnly->setChecked(contestingOnly_);
  ui_->cbZZ00->setChecked(ZZ00_);
  ui_->cbLog4digitGrids->setChecked(log4digitGrids_);
  ui_->decodes_from_top_check_box->setChecked (decodes_from_top_);
  ui_->insert_blank_check_box->setChecked (insert_blank_);
  ui_->cb_detailed_blank_line->setChecked (detailed_blank_);
  ui_->DXCC_check_box->setChecked (DXCC_);
  ui_->ppfx_check_box->setChecked (ppfx_);
  ui_->show_country_names_check_box->setChecked (show_country_names_);
  if (!ui_->DXCC_check_box->isChecked()) {
    ui_->ppfx_check_box->setEnabled (false);
    ui_->show_country_names_check_box->setEnabled (false);
  }
  ui_->Map_Grid_to_State->setChecked(gridMap_);
  ui_->Map_All_Messages->setChecked(gridMapAll_);
  ui_->miles_check_box->setChecked (miles_);
  ui_->quick_call_check_box->setChecked (quick_call_);
  ui_->disable_TX_on_73_check_box->setChecked (disable_TX_on_73_);
  ui_->force_call_1st_check_box->setChecked (force_call_1st_);
  ui_->alternate_bindings_check_box->setChecked (alternate_bindings_);
  ui_->tx_watchdog_spin_box->setValue (watchdog_);
  ui_->tune_watchdog_check_box->setChecked(tune_watchdog_);
  ui_->tune_watchdog_spin_box->setValue (tune_watchdog_time_);
  ui_->TX_messages_check_box->setChecked (TX_messages_);
  ui_->enable_VHF_features_check_box->setChecked(enable_VHF_features_);
  ui_->decode_at_52s_check_box->setChecked(decode_at_52s_);
  ui_->kHz_without_k_check_box->setChecked(kHz_without_k_);
  ui_->disable_button_coloring_check_box->setChecked(button_coloring_disabled_);
  ui_->enable_Wait_features_check_box->setChecked(Wait_features_enabled_);
  ui_->cb_showDistance->setChecked(showDistance_);
  ui_->cb_showAzimuth->setChecked(showAzimuth_);
  ui_->cb_Align->setChecked(align_);
  ui_->repeat_Tx_check_box->setChecked(repeat_Tx_);
  ui_->auto_astro_check_box->setChecked(auto_astro_);
  ui_->single_decode_check_box->setChecked(single_decode_);
  ui_->cbTwoPass->setChecked(twoPass_);
  ui_->cbHighDPI->setChecked(highDPI_);
  ui_->cbLargerTabWidget->setChecked(largerTabWidget_);
  ui_->cbSuperFox->setChecked(bSuperFox_);
  ui_->cbContestName->setChecked(Individual_Contest_Name_);
  ui_->cb_NCCC_Sprint->setChecked(NCCC_Sprint_);
  ui_->cbBlacklist->setChecked(Blacklisted_);
  ui_->cbWhitelist->setChecked(Whitelisted_);
  ui_->cbPass->setChecked(AlwaysPass_);
  ui_->cb_filters_for_Wait_and_Pounce_only->setChecked(filters_for_Wait_and_Pounce_only_);
  ui_->cb_filters_for_word2->setChecked(filters_for_word2_);
  ui_->cb_twoDays->setChecked(twoDays_);
  ui_->gbSpecialOpActivity->setChecked(bSpecialOp_);
  ui_->gbCloudlog->setChecked(bCloudLog_);
  ui_->leCloudlogApiUrl->setText(cloudLogApiUrl_);
  ui_->leCloudlogApiKey->setText(cloudLogApiKey_);
  ui_->sbCloudlogStationID->setValue (cloudLogStationID_);
  ui_->special_op_activity_button_group->button (SelectedActivity_)->setChecked (true);
  ui_->cbx2ToneSpacing->setChecked(x2ToneSpacing_);
  ui_->cbx4ToneSpacing->setChecked(x4ToneSpacing_);
  ui_->type_2_msg_gen_combo_box->setCurrentIndex (type_2_msg_gen_);
  ui_->rig_combo_box->setCurrentText (rig_params_.rig_name);
  ui_->TX_mode_button_group->button (data_mode_)->setChecked (true);
  ui_->split_mode_button_group->button (rig_params_.split_mode)->setChecked (true);
  ui_->CAT_serial_baud_combo_box->setCurrentText (QString::number (rig_params_.baud));
  ui_->CAT_data_bits_button_group->button (rig_params_.data_bits)->setChecked (true);
  ui_->CAT_stop_bits_button_group->button (rig_params_.stop_bits)->setChecked (true);
  ui_->CAT_handshake_button_group->button (rig_params_.handshake)->setChecked (true);
  ui_->cbSortAlphabetically->setChecked(sortAlphabetically_);
  ui_->cbHideCARD->setChecked(hideCARD_);
  ui_->checkBoxAzElExtraLines->setChecked(AzElExtraLines_);
  ui_->checkBoxPwrBandTxMemory->setChecked(pwrBandTxMemory_);
  ui_->checkBoxPwrBandTuneMemory->setChecked(pwrBandTuneMemory_);
  if (rig_params_.force_dtr)
    {
      ui_->force_DTR_combo_box->setCurrentIndex (rig_params_.dtr_high ? 1 : 2);
    }
  else
    {
      ui_->force_DTR_combo_box->setCurrentIndex (0);
    }
  if (rig_params_.force_rts)
    {
      ui_->force_RTS_combo_box->setCurrentIndex (rig_params_.rts_high ? 1 : 2);
    }
  else
    {
      ui_->force_RTS_combo_box->setCurrentIndex (0);
    }
  ui_->TX_audio_source_button_group->button (rig_params_.audio_source)->setChecked (true);
  ui_->CAT_poll_interval_spin_box->setValue (rig_params_.poll_interval & 0x7fff);
  ui_->opCallEntry->setText (opCall_);
  ui_->udp_server_line_edit->setEnabled(false);
  ui_->udp_server_line_edit->setText (udp_server_name_);
  ui_->udp_server_line_edit->setEnabled(true);
  on_udp_server_line_edit_editingFinished ();
  ui_->udp_server_port_spin_box->setValue (udp_server_port_);
  load_network_interfaces (ui_->udp_interfaces_combo_box, udp_interface_names_);
  if (!udp_interface_names_.size ())
    {
      udp_interface_names_ = get_selected_network_interfaces (ui_->udp_interfaces_combo_box);
    }
  ui_->udp_TTL_spin_box->setValue (udp_TTL_);
  ui_->accept_udp_requests_check_box->setChecked (accept_udp_requests_);
  ui_->n1mm_server_name_line_edit->setText (n1mm_server_name_);
  ui_->n1mm_server_port_spin_box->setValue (n1mm_server_port_);
  ui_->enable_n1mm_broadcast_check_box->setChecked (broadcast_to_n1mm_);
  ui_->udpWindowToFront->setChecked(udpWindowToFront_);
  ui_->udpWindowRestore->setChecked(udpWindowRestore_);
  ui_->calibration_intercept_spin_box->setValue (calibration_.intercept);
  ui_->calibration_slope_ppm_spin_box->setValue (calibration_.slope_ppm);
  ui_->rbLowSidelobes->setChecked(bLowSidelobes_);
  if(!bLowSidelobes_) ui_->rbMaxSensitivity->setChecked(true);

  if (rig_params_.ptt_port.isEmpty ())
    {
      if (ui_->PTT_port_combo_box->count ())
        {
          ui_->PTT_port_combo_box->setCurrentText (ui_->PTT_port_combo_box->itemText (0));
        }
    }
  else
    {
      ui_->PTT_port_combo_box->setCurrentText (rig_params_.ptt_port);
    }

  ui_->region_combo_box->setCurrentIndex (region_);

  next_macros_.setStringList (macros_.stringList ());
  next_frequencies_.frequency_list (frequencies_.frequency_list ());
  next_stations_.station_list (stations_.station_list ());

  next_decode_highlighing_model_.items (decode_highlighing_model_.items ());
  ui_->highlight_by_mode_check_box->setChecked (highlight_by_mode_);
  ui_->only_fields_check_box->setChecked (highlight_only_fields_);
  ui_->include_WAE_check_box->setChecked (include_WAE_entities_);
  ui_->highlight_73_check_box->setChecked (highlight_73_);
  ui_->highlight_orange_check_box->setChecked (highlight_orange_);
  ui_->highlight_blue_check_box->setChecked (highlight_blue_);
  ui_->alternate_erase_button_check_box->setChecked (alternate_erase_button_);
  ui_->LotW_days_since_upload_spin_box->setValue (LotW_days_since_upload_);
  ui_->cbHighlightDXcall->setChecked(highlight_DXcall_);
  ui_->cbClearDXcall->setChecked(clear_DXcall_);
  ui_->cbHighlightDXgrid->setChecked(highlight_DXgrid_);
  ui_->cbClearDXgrid->setChecked(clear_DXgrid_);
  ui_->cbEraseBandActivity->setChecked(erase_BandActivity_);
  ui_->cbRxToTxAfterQSO->setChecked(set_RXtoTX_);
  ui_->cbCQ->setChecked(alert_CQ_);
  ui_->cbMyCall->setChecked(alert_MyCall_);
  ui_->cbDXCC->setChecked(alert_DXCC_);
  ui_->cbDXCCOB->setChecked(alert_DXCCOB_);
  ui_->cbGrid->setChecked(alert_Grid_);
  ui_->cbGridOB->setChecked(alert_GridOB_);
  ui_->cbContinent->setChecked(alert_Continent_);
  ui_->cbContinentOB->setChecked(alert_ContinentOB_);
  ui_->cbCQZ->setChecked(alert_CQZ_);
  ui_->cbCQZOB->setChecked(alert_CQZOB_);
  ui_->cbITUZ->setChecked(alert_ITUZ_);
  ui_->cbITUZOB->setChecked(alert_ITUZOB_);
  ui_->cbDXcall->setChecked(alert_DXcall_);
  ui_->cbQSYmessage->setChecked(alert_QSYmessage_);
  ui_->pbAlerts->setChecked(alert_Enabled_);

  ui_->pbTestCloudlog->setStyleSheet ("QPushButton {background-color: none;}");

  check_visibility ();

  set_rig_invariants ();
}

void Configuration::impl::done (int r)
{
  // do this here since window is still on screen at this point
  SettingsGroup g {settings_, "Configuration"};
  settings_->setValue ("window/geometry", saveGeometry ());
  handle_leavingSettings();

  QDialog::done (r);
}

void Configuration::impl::read_settings ()
{
  SettingsGroup g {settings_, "Configuration"};
  LOG_INFO(QString{"Configuration Settings (%1)"}.arg(settings_->fileName()));
  QStringList keys = settings_->allKeys();

  restoreGeometry (settings_->value ("window/geometry").toByteArray ());

  my_callsign_ = settings_->value ("MyCall", QString {}).toString ();
  my_grid_ = settings_->value ("MyGrid", QString {}).toString ();
  FD_exchange_ = settings_->value ("Field_Day_Exchange",QString {}).toString ();
  RTTY_exchange_ = settings_->value ("RTTY_Exchange",QString {}).toString ();
  Contest_Name_ = settings_->value ("Contest_Name",QString {}).toString ();
  ui_->Field_Day_Exchange->setText(FD_exchange_);
  ui_->RTTY_Exchange->setText(RTTY_exchange_);
  ui_->Contest_Name->setText(Contest_Name_);

  Blacklist1_ = settings_->value ("Blacklist1",QString {}).toString ();
  Blacklist2_ = settings_->value ("Blacklist2",QString {}).toString ();
  Blacklist3_ = settings_->value ("Blacklist3",QString {}).toString ();
  Blacklist4_ = settings_->value ("Blacklist4",QString {}).toString ();
  Blacklist5_ = settings_->value ("Blacklist5",QString {}).toString ();
  Blacklist6_ = settings_->value ("Blacklist6",QString {}).toString ();
  Blacklist7_ = settings_->value ("Blacklist7",QString {}).toString ();
  Blacklist8_ = settings_->value ("Blacklist8",QString {}).toString ();
  Blacklist9_ = settings_->value ("Blacklist9",QString {}).toString ();
  Blacklist10_ = settings_->value ("Blacklist10",QString {}).toString ();
  Blacklist11_ = settings_->value ("Blacklist11",QString {}).toString ();
  Blacklist12_ = settings_->value ("Blacklist12",QString {}).toString ();
  Whitelist1_ = settings_->value ("Whitelist1",QString {}).toString ();
  Whitelist2_ = settings_->value ("Whitelist2",QString {}).toString ();
  Whitelist3_ = settings_->value ("Whitelist3",QString {}).toString ();
  Whitelist4_ = settings_->value ("Whitelist4",QString {}).toString ();
  Whitelist5_ = settings_->value ("Whitelist5",QString {}).toString ();
  Whitelist6_ = settings_->value ("Whitelist6",QString {}).toString ();
  Whitelist7_ = settings_->value ("Whitelist7",QString {}).toString ();
  Whitelist8_ = settings_->value ("Whitelist8",QString {}).toString ();
  Whitelist9_ = settings_->value ("Whitelist9",QString {}).toString ();
  Whitelist10_ = settings_->value ("Whitelist10",QString {}).toString ();
  Whitelist11_ = settings_->value ("Whitelist11",QString {}).toString ();
  Whitelist12_ = settings_->value ("Whitelist12",QString {}).toString ();
  Pass1_ = settings_->value ("Pass1",QString {}).toString ();
  Pass2_ = settings_->value ("Pass2",QString {}).toString ();
  Pass3_ = settings_->value ("Pass3",QString {}).toString ();
  Pass4_ = settings_->value ("Pass4",QString {}).toString ();
  Pass5_ = settings_->value ("Pass5",QString {}).toString ();
  Pass6_ = settings_->value ("Pass6",QString {}).toString ();
  Pass7_ = settings_->value ("Pass7",QString {}).toString ();
  Pass8_ = settings_->value ("Pass8",QString {}).toString ();
  Pass9_ = settings_->value ("Pass9",QString {}).toString ();
  Pass10_ = settings_->value ("Pass10",QString {}).toString ();
  Pass11_ = settings_->value ("Pass11",QString {}).toString ();
  Pass12_ = settings_->value ("Pass12",QString {}).toString ();
  Territory1_ = settings_->value ("Territory1",QString {}).toString ();
  Territory2_ = settings_->value ("Territory2",QString {}).toString ();
  Territory3_ = settings_->value ("Territory3",QString {}).toString ();
  Territory4_ = settings_->value ("Territory4",QString {}).toString ();
  highlight_orange_callsigns_ = settings_->value ("HighlightOrangeCallsigns",QString {}).toString ();
  highlight_blue_callsigns_ = settings_->value ("HighlightBlueCallsigns",QString {}).toString ();
  hamlib_backed_up_ = settings_->value ("HamlibBackedUp",QString {}).toString ();
  ui_->Blacklist1->setText(Blacklist1_);
  ui_->Blacklist2->setText(Blacklist2_);
  ui_->Blacklist3->setText(Blacklist3_);
  ui_->Blacklist4->setText(Blacklist4_);
  ui_->Blacklist5->setText(Blacklist5_);
  ui_->Blacklist6->setText(Blacklist6_);
  ui_->Blacklist7->setText(Blacklist7_);
  ui_->Blacklist8->setText(Blacklist8_);
  ui_->Blacklist9->setText(Blacklist9_);
  ui_->Blacklist10->setText(Blacklist10_);
  ui_->Blacklist11->setText(Blacklist11_);
  ui_->Blacklist12->setText(Blacklist12_);
  ui_->Whitelist1->setText(Whitelist1_);
  ui_->Whitelist2->setText(Whitelist2_);
  ui_->Whitelist3->setText(Whitelist3_);
  ui_->Whitelist4->setText(Whitelist4_);
  ui_->Whitelist5->setText(Whitelist5_);
  ui_->Whitelist6->setText(Whitelist6_);
  ui_->Whitelist7->setText(Whitelist7_);
  ui_->Whitelist8->setText(Whitelist8_);
  ui_->Whitelist9->setText(Whitelist9_);
  ui_->Whitelist10->setText(Whitelist10_);
  ui_->Whitelist11->setText(Whitelist11_);
  ui_->Whitelist12->setText(Whitelist12_);
  ui_->Pass1->setText(Pass1_);
  ui_->Pass2->setText(Pass2_);
  ui_->Pass3->setText(Pass3_);
  ui_->Pass4->setText(Pass4_);
  ui_->Pass5->setText(Pass5_);
  ui_->Pass6->setText(Pass6_);
  ui_->Pass7->setText(Pass7_);
  ui_->Pass8->setText(Pass8_);
  ui_->Pass9->setText(Pass9_);
  ui_->Pass10->setText(Pass10_);
  ui_->Pass11->setText(Pass11_);
  ui_->Pass12->setText(Pass12_);
  ui_->Territory1->setText(Territory1_);
  ui_->Territory2->setText(Territory2_);
  ui_->Territory3->setText(Territory3_);
  ui_->Territory4->setText(Territory4_);
  ui_->highlight_orange_callsigns->setText(highlight_orange_callsigns_);
  ui_->highlight_blue_callsigns->setText(highlight_blue_callsigns_);
  PWR_and_SWR_ = settings_->value ("PWRandSWR", false).toBool ();
  check_SWR_ = settings_->value ("CheckSWR", false).toBool ();

  OTPinterval_ = settings_->value ("OTPinterval", 1).toUInt ();
  OTPUrl_ = settings_->value ("OTPUrl", FoxVerifier::default_url()).toString ();
  OTPSeed_ = settings_->value ("OTPSeed", QString {}).toString ();
  OTPEnabled_ = settings_->value ("OTPEnabled", false).toBool ();
  ShowOTP_ = settings_->value ("ShowOTP", false).toBool ();

  ui_->sbOTPinterval->setValue(OTPinterval_);
  ui_->OTPUrl->setText(OTPUrl_);
  ui_->OTPSeed->setText(OTPSeed_);
  ui_->cbOTP->setChecked(OTPEnabled_);
  ui_->cbShowOTP->setChecked(ShowOTP_);


  if (next_font_.fromString (settings_->value ("Font", QGuiApplication::font ().toString ()).toString ())
      && next_font_ != font_)
    {
      font_ = next_font_;
      Q_EMIT self_->text_font_changed (font_);
    }
  else
    {
      next_font_ = font_;
    }
  if (next_decoded_text_font_.fromString (settings_->value ("DecodedTextFont", "Courier, 10").toString ())
      && next_decoded_text_font_ != decoded_text_font_)
    {
      decoded_text_font_ = next_decoded_text_font_;
      next_decode_highlighing_model_.set_font (decoded_text_font_);
      ui_->highlighting_list_view->reset ();
      Q_EMIT self_->decoded_text_font_changed (decoded_text_font_);
    }
  else
    {
      next_decoded_text_font_ = decoded_text_font_;
    }

  id_interval_ = settings_->value ("IDint", 0).toInt ();
  align_steps_ = settings_->value ("AlignSteps", 2).toInt ();
  align_steps2_ = settings_->value ("AlignSteps2", 0).toInt ();
  ntrials_ = settings_->value ("nTrials", 6).toInt ();
  volume_ = settings_->value ("volume", 0).toInt ();
  txDelay_ = settings_->value ("TxDelay",0.2).toDouble();
  aggressive_ = settings_->value ("Aggressive", 4).toInt ();
  RxBandwidth_ = settings_->value ("RxBandwidth", 2500).toInt ();
  save_directory_.setPath (settings_->value ("SaveDir", default_save_directory_.absolutePath ()).toString ());
  azel_directory_.setPath (settings_->value ("AzElDir", default_azel_directory_.absolutePath ()).toString ());

  tci_audio_ = settings_->value ("TCIAudio", tci_audio_).toBool ();

  type_2_msg_gen_ = settings_->value ("Type2MsgGen", QVariant::fromValue (Configuration::type_2_msg_3_full)).value<Configuration::Type2MsgGen> ();

  monitor_off_at_startup_ = settings_->value ("MonitorOFF", false).toBool ();
  monitor_last_used_ = settings_->value ("MonitorLastUsed", false).toBool ();
  spot_to_psk_reporter_ = settings_->value ("PSKReporter", false).toBool ();
  psk_reporter_tcpip_ = settings_->value ("PSKReporterTCPIP", false).toBool ();
  id_after_73_ = settings_->value ("After73", false).toBool ();
  tx_QSY_allowed_ = settings_->value ("TxQSYAllowed", false).toBool ();
  progressBar_red_ = settings_->value ("ProgressBarRed", true).toBool ();
  use_dynamic_grid_ = settings_->value ("AutoGrid", false).toBool ();

  macros_.setStringList (settings_->value ("Macros", QStringList {"TNX 73 GL"}).toStringList ());

  region_ = settings_->value ("Region", QVariant::fromValue (IARURegions::ALL)).value<IARURegions::Region> ();

  LOG_INFO(QString{"Reading frequencies"});

  if (settings_->contains ("FrequenciesForRegionModes_v2"))
    {
      LOG_INFO(QString{"read_settings found FrequenciesForRegionModes_v2"});
      if (settings_->contains ("FrequenciesForRegionModes"))
        {
          LOG_INFO(QString{"read_settings ALSO found FrequenciesForRegionModes"});
        }

      auto const& v = settings_->value ("FrequenciesForRegionModes_v2");
      if (v.isValid ())
        {
          frequencies_.frequency_list (v.value<FrequencyList_v2_101::FrequencyItems> ());
        }
      else
        {
          frequencies_.reset_to_defaults ();
        }
    }
  else
    {
      LOG_INFO(QString{"read_settings looking for FrequenciesForRegionModes"});
      if (settings_->contains ("FrequenciesForRegionModes")) // has the old ones.
        {
          LOG_INFO(QString{"found FrequenciesForRegionModes"});
          auto const& v = settings_->value("FrequenciesForRegionModes");
          LOG_INFO(QString{"v is %1"}.arg(v.typeName()));
          if (v.isValid())
            {
              LOG_INFO(QString{"read_settings found VALID FrequenciesForRegionModes"});
              FrequencyList_v2_101::FrequencyItems list;
              FrequencyList_v2::FrequencyItems v100 = v.value<FrequencyList_v2::FrequencyItems>();
              LOG_INFO(QString{"read_settings read %1 old_format items from FrequenciesForRegionModes"}.arg(v100.size()));

              Q_FOREACH (auto const& item, v100)
              {
                list << FrequencyList_v2_101::Item{item.frequency_, item.mode_, item.region_, QString(), QString(), QDateTime(),
                                               QDateTime(), false};
              }
              LOG_INFO(QString{"converted %1 items to FrequenciesForRegionModes_v2"}.arg(list.size()));

              frequencies_.frequency_list(list);
            }
            else
            {
              LOG_INFO(QString{"read_settings INVALID FrequenciesForRegionModes"});
              frequencies_.reset_to_defaults();
            }
        }
      else
        {
          frequencies_.reset_to_defaults();
        }
    }

  stations_.station_list (settings_->value ("stations").value<StationList::Stations> ());

  auto highlight_items = settings_->value ("DecodeHighlighting", QVariant::fromValue (DecodeHighlightingModel::default_items ())).value<DecodeHighlightingModel::HighlightItems> ();
  if (!highlight_items.size ()) highlight_items = DecodeHighlightingModel::default_items ();
  decode_highlighing_model_.items (highlight_items);
  highlight_by_mode_ = settings_->value("HighlightByMode", false).toBool ();
  highlight_only_fields_ = settings_->value("OnlyFieldsSought", false).toBool ();
  include_WAE_entities_ = settings_->value("IncludeWAEEntities", false).toBool ();
  highlight_73_ = settings_->value("Highlight73", true).toBool ();
  highlight_orange_ = settings_->value("HighlightOrange", false).toBool ();
  highlight_blue_ = settings_->value("HighlightBlue", false).toBool ();
  alternate_erase_button_ = settings_->value("AlternateEraseButtonBehavior", true).toBool ();
  show_country_names_ = settings_->value("AlwaysShowCountryNames", false).toBool ();
  LotW_days_since_upload_ = settings_->value ("LotWDaysSinceLastUpload", 365).toInt ();
  lotw_users_.set_age_constraint (LotW_days_since_upload_);

  log_as_RTTY_ = settings_->value ("toRTTY", false).toBool ();
  report_in_comments_ = settings_->value("dBtoComments", false).toBool ();
  specOp_in_comments_ = settings_->value("specOptoComments", false).toBool ();
  rig_params_.rig_name = settings_->value ("Rig", TransceiverFactory::basic_transceiver_name_).toString ();
  rig_is_dummy_ = TransceiverFactory::basic_transceiver_name_ == rig_params_.rig_name;
  is_tci_ = rig_params_.rig_name.startsWith("TCI Cli");
  rig_params_.tci_port = settings_->value ("CATTCIPort","").toString ();
  rig_params_.network_port = settings_->value ("CATNetworkPort").toString ();
  rig_params_.usb_port = settings_->value ("CATUSBPort").toString ();
  rig_params_.serial_port = settings_->value ("CATSerialPort").toString ();
  rig_params_.baud = settings_->value ("CATSerialRate", 4800).toInt ();
  rig_params_.data_bits = settings_->value ("CATDataBits", QVariant::fromValue (TransceiverFactory::default_data_bits)).value<TransceiverFactory::DataBits> ();
  rig_params_.stop_bits = settings_->value ("CATStopBits", QVariant::fromValue (TransceiverFactory::default_stop_bits)).value<TransceiverFactory::StopBits> ();
  rig_params_.handshake = settings_->value ("CATHandshake", QVariant::fromValue (TransceiverFactory::handshake_default)).value<TransceiverFactory::Handshake> ();
  rig_params_.force_dtr = settings_->value ("CATForceDTR", false).toBool ();
  rig_params_.dtr_high = settings_->value ("DTR", false).toBool ();
  rig_params_.force_rts = settings_->value ("CATForceRTS", false).toBool ();
  rig_params_.rts_high = settings_->value ("RTS", false).toBool ();
  rig_params_.ptt_type = settings_->value ("PTTMethod", QVariant::fromValue (TransceiverFactory::PTT_method_VOX)).value<TransceiverFactory::PTTMethod> ();
  rig_params_.audio_source = settings_->value ("TXAudioSource", QVariant::fromValue (TransceiverFactory::TX_audio_source_front)).value<TransceiverFactory::TXAudioSource> ();
  rig_params_.ptt_port = settings_->value ("PTTport").toString ();
  data_mode_ = settings_->value ("DataMode", QVariant::fromValue (data_mode_none)).value<Configuration::DataMode> ();
  bLowSidelobes_ = settings_->value("LowSidelobes",true).toBool();
  prompt_to_log_ = settings_->value ("PromptToLog", false).toBool ();
  autoLog_ = settings_->value ("AutoLog", true).toBool ();
  contestingOnly_ = settings_->value ("ContestingOnly", true).toBool ();
  ZZ00_ = settings_->value("ZZ00",false).toBool ();
  log4digitGrids_ = settings_->value ("Log4digitGrids", false).toBool ();
  decodes_from_top_ = settings_->value ("DecodesFromTop", false).toBool ();
  insert_blank_ = settings_->value ("InsertBlank", true).toBool ();
  detailed_blank_ = settings_->value ("DetailedBlank", true).toBool ();
  DXCC_ = settings_->value ("DXCCEntity", true).toBool ();
  gridMap_ = settings_->value("MapGridEntity", true).toBool();
  gridMapAll_ = settings_->value("MapGridAllEntity", true).toBool();
  ppfx_ = settings_->value ("PrincipalPrefix", false).toBool ();
  miles_ = settings_->value ("Miles", false).toBool ();
  quick_call_ = settings_->value ("QuickCall", true).toBool ();
  disable_TX_on_73_ = settings_->value ("73TxDisable", true).toBool ();
  force_call_1st_ = settings_->value ("ForceCallFirst", false).toBool ();
  alternate_bindings_ = settings_->value ("AlternateBindings", false).toBool ();
  watchdog_ = settings_->value ("TxWatchdog", 6).toInt ();
  tune_watchdog_ = settings_->value("TuneWatchdog",true).toBool ();
  tune_watchdog_time_ = settings_->value ("TuneWatchdogTime", 90).toInt ();
  TX_messages_ = settings_->value ("Tx2QSO", true).toBool ();
  enable_VHF_features_ = settings_->value("VHFUHF",false).toBool ();
  decode_at_52s_ = settings_->value("Decode52",false).toBool ();
  kHz_without_k_ = settings_->value("kHzWithoutK",false).toBool ();
  button_coloring_disabled_ = settings_->value("TxWarningDisabled",false).toBool ();
  Wait_features_enabled_ = settings_->value("WaitFeaturesEnabled",true).toBool ();
  showDistance_ = settings_->value("showDistance", false).toBool();
  showAzimuth_ = settings_->value("showAzimuth", false).toBool();
  align_ = settings_->value("AlignDistanceAzimuth", true).toBool();
  repeat_Tx_ = settings_->value("RepeatTx",false).toBool ();
  auto_astro_ = settings_->value("AutoAstroWindow",false).toBool ();
  single_decode_ = settings_->value("SingleDecode",false).toBool ();
  twoPass_ = settings_->value("TwoPass",true).toBool ();
  highDPI_ = settings_->value("HighDPI",true).toBool ();
  largerTabWidget_ = settings_->value("LargerTabWidget",false).toBool ();
  bSuperFox_ = settings_->value("SuperFox",true).toBool ();
  Individual_Contest_Name_ = settings_->value("Individual_Contest_Name",false).toBool ();
  NCCC_Sprint_ = settings_->value("NCCC_Sprint",false).toBool ();
  Blacklisted_ = settings_->value("Blacklisted",false).toBool ();
  Whitelisted_ = settings_->value("Whitelisted",false).toBool ();
  AlwaysPass_ = settings_->value("AlwaysPass",false).toBool ();
  filters_for_Wait_and_Pounce_only_ = settings_->value("FiltersForWaitAndPounceOnly",false).toBool ();
  filters_for_word2_ = settings_->value("FiltersForWord2",false).toBool ();
  twoDays_ = settings_->value("TwoDays",false).toBool ();
  bSpecialOp_ = settings_->value("SpecialOpActivity",false).toBool ();
  bCloudLog_ = settings_->value("CloudLog",false).toBool ();
  cloudLogApiUrl_ = settings_->value ("CloudLogApiUrl", QString {}).toString ();
  cloudLogApiKey_ = settings_->value ("CloudLogApiKey", QString {}).toString ();
  cloudLogStationID_ = settings_->value("CloudLogStationID",1).toInt ();
  SelectedActivity_ = settings_->value("SelectedActivity",1).toInt ();
  x2ToneSpacing_ = settings_->value("x2ToneSpacing",false).toBool ();
  x4ToneSpacing_ = settings_->value("x4ToneSpacing",false).toBool ();
  rig_params_.poll_interval = settings_->value ("Polling", 0).toInt ();
  rig_params_.split_mode = settings_->value ("SplitMode", QVariant::fromValue (TransceiverFactory::split_mode_none)).value<TransceiverFactory::SplitMode> ();
  opCall_ = settings_->value ("OpCall", "").toString ();
  udp_server_name_ = settings_->value ("UDPServer", "127.0.0.1").toString ();
  udp_interface_names_ = settings_->value ("UDPInterface").toStringList ();
  udp_TTL_ = settings_->value ("UDPTTL", 1).toInt ();
  udp_server_port_ = settings_->value ("UDPServerPort", 2237).toUInt ();
  n1mm_server_name_ = settings_->value ("N1MMServer", "127.0.0.1").toString ();
  n1mm_server_port_ = settings_->value ("N1MMServerPort", 2333).toUInt ();
  broadcast_to_n1mm_ = settings_->value ("BroadcastToN1MM", false).toBool ();
  accept_udp_requests_ = settings_->value ("AcceptUDPRequests", false).toBool ();
  udpWindowToFront_ = settings_->value ("udpWindowToFront",false).toBool ();
  udpWindowRestore_ = settings_->value ("udpWindowRestore",false).toBool ();
  calibration_.intercept = settings_->value ("CalibrationIntercept", 0.).toDouble ();
  calibration_.slope_ppm = settings_->value ("CalibrationSlopePPM", 0.).toDouble ();
  sortAlphabetically_ = settings_->value("SortAlphabetically",true).toBool ();
  hideCARD_ = settings_->value("HideCARD",true).toBool ();
  AzElExtraLines_ = settings_->value("AzElExtraLines",false).toBool ();
  pwrBandTxMemory_ = settings_->value("pwrBandTxMemory",false).toBool ();
  pwrBandTuneMemory_ = settings_->value("pwrBandTuneMemory",false).toBool ();
  highlight_DXcall_ = settings_->value("highlight_DXcall",true).toBool ();
  clear_DXcall_ = settings_->value("clear_DXcall",false).toBool ();
  highlight_DXgrid_ = settings_->value("highlight_DXgrid",true).toBool ();
  clear_DXgrid_ = settings_->value("clear_DXgrid",false).toBool ();
  erase_BandActivity_ = settings_->value("erase_BandActivity",false).toBool ();
  set_RXtoTX_ = settings_->value("set_RXtoTX",false).toBool ();
  alert_CQ_ = settings_->value("alert_CQ",false).toBool ();
  alert_MyCall_ = settings_->value("alert_MyCall",false).toBool ();
  alert_DXCC_ = settings_->value("alert_DXCC",false).toBool ();
  alert_DXCCOB_ = settings_->value("alert_DXCCOB",false).toBool ();
  alert_Grid_ = settings_->value("alert_Grid",false).toBool ();
  alert_GridOB_ = settings_->value("alert_GridOB",false).toBool ();
  alert_Continent_ = settings_->value("alert_Continent",false).toBool ();
  alert_ContinentOB_ = settings_->value("alert_ContinentOB",false).toBool ();
  alert_CQZ_ = settings_->value("alert_CQZ",false).toBool ();
  alert_CQZOB_ = settings_->value("alert_CQZOB",false).toBool ();
  alert_ITUZ_ = settings_->value("alert_ITUZ",false).toBool ();
  alert_ITUZOB_ = settings_->value("alert_ITUZOB",false).toBool ();
  alert_DXcall_ = settings_->value("alert_DXcall",false).toBool ();
  alert_QSYmessage_ = settings_->value("alert_QSYmessage",false).toBool ();
  alert_Enabled_ = settings_->value("alert_Enabled",false).toBool ();
  // Reset Rig to None if TCI was selected but no IP address was specified
  if (is_tci_ && settings_->value("CATTCIPort")=="") {
    rig_params_.rig_name = "None";
    if (rig_params_.ptt_type == TransceiverFactory::PTT_method_CAT) rig_params_.ptt_type = TransceiverFactory::PTT_method_VOX;
  }
#ifdef WIN32
  QTimer::singleShot (2500, [=] {display_file_information ();});
#else
  ui_->hamlib_groupBox->setTitle("Hamlib Version");
  ui_->rbHamlib64->setVisible(false);
  ui_->rbHamlib32->setVisible(false);
  ui_->hamlib_download_button->setVisible(false);
  ui_->revert_update_button->setVisible(false);
  ui_->backed_up_text->setVisible(false);
  ui_->backed_up->setVisible(false);
  QTimer::singleShot (2500, [=] {display_file_information ();});
#endif
}

void Configuration::impl::find_audio_devices ()
{
  //
  // retrieve audio input device
  //
  auto saved_name = settings_->value ("SoundInName").toString ();
  if (is_tci_ && tci_audio_) saved_name = "TCI audio";  // TCI
  if (next_audio_input_device_.deviceName () != saved_name || next_audio_input_device_.isNull ())
    {
      next_audio_input_device_ = find_audio_device (QAudio::AudioInput, ui_->sound_input_combo_box, saved_name);
      next_audio_input_channel_ = AudioDevice::fromString (settings_->value ("AudioInputChannel", "Mono").toString ());
      update_audio_channels (ui_->sound_input_combo_box, ui_->sound_input_combo_box->currentIndex (), ui_->sound_input_channel_combo_box, false);
      ui_->sound_input_channel_combo_box->setCurrentIndex (next_audio_input_channel_);
    }
  //
  // retrieve audio output device
  //
  saved_name = settings_->value("SoundOutName").toString();
  if (is_tci_ && tci_audio_) saved_name = "TCI audio";  // TCI
  if (next_audio_output_device_.deviceName () != saved_name || next_audio_output_device_.isNull ())
    {
      next_audio_output_device_ = find_audio_device (QAudio::AudioOutput, ui_->sound_output_combo_box, saved_name);
      next_audio_output_channel_ = AudioDevice::fromString (settings_->value ("AudioOutputChannel", "Mono").toString ());
      update_audio_channels (ui_->sound_output_combo_box, ui_->sound_output_combo_box->currentIndex (), ui_->sound_output_channel_combo_box, true);
      ui_->sound_output_channel_combo_box->setCurrentIndex (next_audio_output_channel_);
    }
}

void Configuration::impl::write_settings ()
{
  SettingsGroup g {settings_, "Configuration"};

  settings_->setValue ("MyCall", my_callsign_);
  settings_->setValue ("MyGrid", my_grid_);
  settings_->setValue ("Field_Day_Exchange", FD_exchange_);
  settings_->setValue ("RTTY_Exchange", RTTY_exchange_);
  settings_->setValue ("Contest_Name", Contest_Name_);
  settings_->setValue ("Blacklist1", Blacklist1_);
  settings_->setValue ("Blacklist2", Blacklist2_);
  settings_->setValue ("Blacklist3", Blacklist3_);
  settings_->setValue ("Blacklist4", Blacklist4_);
  settings_->setValue ("Blacklist5", Blacklist5_);
  settings_->setValue ("Blacklist6", Blacklist6_);
  settings_->setValue ("Blacklist7", Blacklist7_);
  settings_->setValue ("Blacklist8", Blacklist8_);
  settings_->setValue ("Blacklist9", Blacklist9_);
  settings_->setValue ("Blacklist10", Blacklist10_);
  settings_->setValue ("Blacklist11", Blacklist11_);
  settings_->setValue ("Blacklist12", Blacklist12_);
  settings_->setValue ("Whitelist1", Whitelist1_);
  settings_->setValue ("Whitelist2", Whitelist2_);
  settings_->setValue ("Whitelist3", Whitelist3_);
  settings_->setValue ("Whitelist4", Whitelist4_);
  settings_->setValue ("Whitelist5", Whitelist5_);
  settings_->setValue ("Whitelist6", Whitelist6_);
  settings_->setValue ("Whitelist7", Whitelist7_);
  settings_->setValue ("Whitelist8", Whitelist8_);
  settings_->setValue ("Whitelist9", Whitelist9_);
  settings_->setValue ("Whitelist10", Whitelist10_);
  settings_->setValue ("Whitelist11", Whitelist11_);
  settings_->setValue ("Whitelist12", Whitelist12_);
  settings_->setValue ("Pass1", Pass1_);
  settings_->setValue ("Pass2", Pass2_);
  settings_->setValue ("Pass3", Pass3_);
  settings_->setValue ("Pass4", Pass4_);
  settings_->setValue ("Pass5", Pass5_);
  settings_->setValue ("Pass6", Pass6_);
  settings_->setValue ("Pass7", Pass7_);
  settings_->setValue ("Pass8", Pass8_);
  settings_->setValue ("Pass9", Pass9_);
  settings_->setValue ("Pass10", Pass10_);
  settings_->setValue ("Pass11", Pass11_);
  settings_->setValue ("Pass12", Pass12_);
  settings_->setValue ("Territory1", Territory1_);
  settings_->setValue ("Territory2", Territory2_);
  settings_->setValue ("Territory3", Territory3_);
  settings_->setValue ("Territory4", Territory4_);
  settings_->setValue ("HighlightOrangeCallsigns", highlight_orange_callsigns_);
  settings_->setValue ("HighlightBlueCallsigns", highlight_blue_callsigns_);
  settings_->setValue ("PWRandSWR", PWR_and_SWR_);
  settings_->setValue ("CheckSWR", check_SWR_);

  settings_->setValue ("Font", font_.toString ());
  settings_->setValue ("DecodedTextFont", decoded_text_font_.toString ());
  settings_->setValue ("IDint", id_interval_);
  settings_->setValue ("AlignSteps", align_steps_);
  settings_->setValue ("AlignSteps2", align_steps2_);
  settings_->setValue ("nTrials", ntrials_);
  settings_->setValue ("volume", volume_);
  settings_->setValue ("TxDelay", txDelay_);
  settings_->setValue ("Aggressive", aggressive_);
  settings_->setValue ("RxBandwidth", RxBandwidth_);
  settings_->setValue ("TCIAudio", tci_audio_);
  settings_->setValue ("CATTCIPort", rig_params_.tci_port);
  settings_->setValue ("PTTMethod", QVariant::fromValue (rig_params_.ptt_type));
  settings_->setValue ("PTTport", rig_params_.ptt_port);
  settings_->setValue ("SaveDir", save_directory_.absolutePath ());
  settings_->setValue ("AzElDir", azel_directory_.absolutePath ());
  if (!audio_input_device_.isNull ()) {
      settings_->setValue ("SoundInName", audio_input_device_.deviceName ());
      settings_->setValue ("AudioInputChannel", AudioDevice::toString (audio_input_channel_));
  } else if (is_tci_ && tci_audio_) {
    settings_->setValue ("SoundInName", "TCI audio");
    settings_->setValue ("AudioInputChannel", "TCI audio");
  }
  if (!audio_output_device_.isNull ()) {
    settings_->setValue ("SoundOutName", audio_output_device_.deviceName ());
    settings_->setValue ("AudioOutputChannel", AudioDevice::toString (audio_output_channel_));
  } else if (is_tci_ && tci_audio_) {
    settings_->setValue ("SoundOutName", "TCI audio");
    settings_->setValue ("AudioOutputChannel", "TCI audio");
  }
  settings_->setValue ("Type2MsgGen", QVariant::fromValue (type_2_msg_gen_));
  settings_->setValue ("MonitorOFF", monitor_off_at_startup_);
  settings_->setValue ("MonitorLastUsed", monitor_last_used_);
  settings_->setValue ("PSKReporter", spot_to_psk_reporter_);
  settings_->setValue ("PSKReporterTCPIP", psk_reporter_tcpip_);
  settings_->setValue ("After73", id_after_73_);
  settings_->setValue ("TxQSYAllowed", tx_QSY_allowed_);
  settings_->setValue ("ProgressBarRed", progressBar_red_);
  settings_->setValue ("Macros", macros_.stringList ());
  settings_->setValue ("stations", QVariant::fromValue (stations_.station_list ()));
  settings_->setValue ("FrequenciesForRegionModes_v2", QVariant::fromValue (frequencies_.frequency_list ()));
  settings_->setValue ("DecodeHighlighting", QVariant::fromValue (decode_highlighing_model_.items ()));
  settings_->setValue ("HighlightByMode", highlight_by_mode_);
  settings_->setValue ("OnlyFieldsSought", highlight_only_fields_);
  settings_->setValue ("IncludeWAEEntities", include_WAE_entities_);
  settings_->setValue ("Highlight73", highlight_73_);
  settings_->setValue ("HighlightOrange", highlight_orange_);
  settings_->setValue ("HighlightBlue", highlight_blue_);
  settings_->setValue ("AlternateEraseButtonBehavior", alternate_erase_button_);
  settings_->setValue ("AlwaysShowCountryNames", show_country_names_);
  settings_->setValue ("LotWDaysSinceLastUpload", LotW_days_since_upload_);
  settings_->setValue ("toRTTY", log_as_RTTY_);
  settings_->setValue ("dBtoComments", report_in_comments_);
  settings_->setValue ("specOptoComments", specOp_in_comments_);
  settings_->setValue ("Rig", rig_params_.rig_name);
  settings_->setValue ("CATNetworkPort", rig_params_.network_port);
  settings_->setValue ("CATUSBPort", rig_params_.usb_port);
  settings_->setValue ("CATSerialPort", rig_params_.serial_port);
  settings_->setValue ("CATSerialRate", rig_params_.baud);
  settings_->setValue ("CATDataBits", QVariant::fromValue (rig_params_.data_bits));
  settings_->setValue ("CATStopBits", QVariant::fromValue (rig_params_.stop_bits));
  settings_->setValue ("CATHandshake", QVariant::fromValue (rig_params_.handshake));
  settings_->setValue ("DataMode", QVariant::fromValue (data_mode_));
  settings_->setValue ("LowSidelobes",bLowSidelobes_);
  settings_->setValue ("PromptToLog", prompt_to_log_);
  settings_->setValue ("AutoLog", autoLog_);
  settings_->setValue ("ContestingOnly", contestingOnly_);
  settings_->setValue ("ZZ00", ZZ00_);
  settings_->setValue ("Log4digitGrids", log4digitGrids_);
  settings_->setValue ("DecodesFromTop", decodes_from_top_);
  settings_->setValue ("InsertBlank", insert_blank_);
  settings_->setValue ("DetailedBlank", detailed_blank_);
  settings_->setValue ("DXCCEntity", DXCC_);
  settings_->setValue ("MapGridEntity", gridMap_);
  settings_->setValue ("MapGridAllEntity", gridMapAll_);
  settings_->setValue ("PrincipalPrefix", ppfx_);
  settings_->setValue ("Miles", miles_);
  settings_->setValue ("QuickCall", quick_call_);
  settings_->setValue ("73TxDisable", disable_TX_on_73_);
  settings_->setValue ("ForceCallFirst", force_call_1st_);
  settings_->setValue ("AlternateBindings", alternate_bindings_);
  settings_->setValue ("TxWatchdog", watchdog_);
  settings_->setValue ("TuneWatchdog", tune_watchdog_);
  settings_->setValue ("TuneWatchdogTime", tune_watchdog_time_);
  settings_->setValue ("Tx2QSO", TX_messages_);
  settings_->setValue ("CATForceDTR", rig_params_.force_dtr);
  settings_->setValue ("DTR", rig_params_.dtr_high);
  settings_->setValue ("CATForceRTS", rig_params_.force_rts);
  settings_->setValue ("RTS", rig_params_.rts_high);
  settings_->setValue ("TXAudioSource", QVariant::fromValue (rig_params_.audio_source));
  settings_->setValue ("Polling", rig_params_.poll_interval);
  settings_->setValue ("SplitMode", QVariant::fromValue (rig_params_.split_mode));
  settings_->setValue ("VHFUHF", enable_VHF_features_);
  settings_->setValue ("Decode52", decode_at_52s_);
  settings_->setValue ("kHzWithoutK", kHz_without_k_);
  settings_->setValue ("TxWarningDisabled", button_coloring_disabled_);
  settings_->setValue ("WaitFeaturesEnabled", Wait_features_enabled_);
  settings_->setValue ("showDistance", showDistance_);
  settings_->setValue ("showAzimuth", showAzimuth_);
  settings_->setValue ("AlignDistanceAzimuth", align_);
  settings_->setValue ("RepeatTx", repeat_Tx_);
  settings_->setValue ("AutoAstroWindow", auto_astro_);
  settings_->setValue ("SingleDecode", single_decode_);
  settings_->setValue ("TwoPass", twoPass_);
  settings_->setValue ("HighDPI", highDPI_);
  settings_->setValue ("LargerTabWidget", largerTabWidget_);
  settings_->setValue ("SuperFox", bSuperFox_);
  settings_->setValue ("Individual_Contest_Name", Individual_Contest_Name_);
  settings_->setValue ("NCCC_Sprint", NCCC_Sprint_);
  settings_->setValue ("Blacklisted", Blacklisted_);
  settings_->setValue ("Whitelisted", Whitelisted_);
  settings_->setValue ("AlwaysPass", AlwaysPass_);
  settings_->setValue ("FiltersForWaitAndPounceOnly", filters_for_Wait_and_Pounce_only_);
  settings_->setValue ("FiltersForWord2", filters_for_word2_);
  settings_->setValue ("TwoDays", twoDays_);
  settings_->setValue ("SelectedActivity", SelectedActivity_);
  settings_->setValue ("SpecialOpActivity", bSpecialOp_);
  settings_->setValue ("CloudLog", bCloudLog_);
  settings_->setValue ("CloudLogApiUrl", cloudLogApiUrl_);
  settings_->setValue ("CloudLogApiKey", cloudLogApiKey_);
  settings_->setValue ("CloudLogStationID", cloudLogStationID_);
  settings_->setValue ("x2ToneSpacing", x2ToneSpacing_);
  settings_->setValue ("x4ToneSpacing", x4ToneSpacing_);
  settings_->setValue ("OpCall", opCall_);
  settings_->setValue ("UDPServer", udp_server_name_);
  settings_->setValue ("UDPServerPort", udp_server_port_);
  settings_->setValue ("UDPInterface", QVariant::fromValue (udp_interface_names_));
  settings_->setValue ("UDPTTL", udp_TTL_);
  settings_->setValue ("N1MMServer", n1mm_server_name_);
  settings_->setValue ("N1MMServerPort", n1mm_server_port_);
  settings_->setValue ("BroadcastToN1MM", broadcast_to_n1mm_);
  settings_->setValue ("AcceptUDPRequests", accept_udp_requests_);
  settings_->setValue ("udpWindowToFront", udpWindowToFront_);
  settings_->setValue ("udpWindowRestore", udpWindowRestore_);
  settings_->setValue ("CalibrationIntercept", calibration_.intercept);
  settings_->setValue ("CalibrationSlopePPM", calibration_.slope_ppm);
  settings_->setValue ("SortAlphabetically", sortAlphabetically_);
  settings_->setValue ("HideCARD", hideCARD_);
  settings_->setValue ("AzElExtraLines", AzElExtraLines_);
  settings_->setValue ("pwrBandTxMemory", pwrBandTxMemory_);
  settings_->setValue ("pwrBandTuneMemory", pwrBandTuneMemory_);
  settings_->setValue ("Region", QVariant::fromValue (region_));
  settings_->setValue ("AutoGrid", use_dynamic_grid_);
  settings_->setValue ("highlight_DXcall", highlight_DXcall_);
  settings_->setValue ("clear_DXcall", clear_DXcall_);
  settings_->setValue ("highlight_DXgrid", highlight_DXgrid_);
  settings_->setValue ("OTPinterval", OTPinterval_);
  settings_->setValue ("OTPUrl", OTPUrl_);
  settings_->setValue ("OTPSeed", OTPSeed_);
  settings_->setValue ("OTPEnabled", OTPEnabled_);
  settings_->setValue ("ShowOTP", ShowOTP_);
  settings_->setValue ("clear_DXgrid", clear_DXgrid_);
  settings_->setValue ("erase_BandActivity", erase_BandActivity_);
  settings_->setValue ("set_RXtoTX", set_RXtoTX_);
  settings_->setValue ("alert_CQ", alert_CQ_);
  settings_->setValue ("alert_MyCall", alert_MyCall_);
  settings_->setValue ("alert_DXCC", alert_DXCC_);
  settings_->setValue ("alert_DXCCOB", alert_DXCCOB_);
  settings_->setValue ("alert_Grid", alert_Grid_);
  settings_->setValue ("alert_GridOB", alert_GridOB_);
  settings_->setValue ("alert_Continent", alert_Continent_);
  settings_->setValue ("alert_ContinentOB", alert_ContinentOB_);
  settings_->setValue ("alert_CQZ", alert_CQZ_);
  settings_->setValue ("alert_CQZOB", alert_CQZOB_);
  settings_->setValue ("alert_ITUZ", alert_ITUZ_);
  settings_->setValue ("alert_ITUZOB", alert_ITUZOB_);
  settings_->setValue ("alert_DXcall", alert_DXcall_);
  settings_->setValue ("alert_QSYmessage", alert_QSYmessage_);
  settings_->setValue ("alert_Enabled", alert_Enabled_);
  settings_->sync ();
}

void Configuration::impl::set_rig_invariants ()
{
  auto const& rig = ui_->rig_combo_box->currentText ();
  auto const& ptt_port = ui_->PTT_port_combo_box->currentText ();
  auto ptt_method = static_cast<TransceiverFactory::PTTMethod> (ui_->PTT_method_button_group->checkedId ());

  auto CAT_PTT_enabled = transceiver_factory_.has_CAT_PTT (rig);
  auto CAT_indirect_serial_PTT = transceiver_factory_.has_CAT_indirect_serial_PTT (rig);
  auto asynchronous_CAT = transceiver_factory_.has_asynchronous_CAT (rig);
  auto is_hw_handshake = ui_->CAT_handshake_group_box->isEnabled ()
    && TransceiverFactory::handshake_hardware == static_cast<TransceiverFactory::Handshake> (ui_->CAT_handshake_button_group->checkedId ());
  is_tci_ = ui_->rig_combo_box->currentText().startsWith("TCI Cli");
  ui_->tci_audio_check_box->setVisible(is_tci_);
  ui_->TCI_spin_box->setVisible(is_tci_);
//  ui_->refresh_push_button->setVisible(is_tci_);
  if (is_tci_ && tci_audio_) {
    find_audio_devices ();
    ui_->sound_input_channel_combo_box->setCurrentIndex (0);
    ui_->sound_output_channel_combo_box->setCurrentIndex (0);
  }
  ui_->test_CAT_push_button->setStyleSheet ({});
  ui_->CAT_poll_interval_label->setEnabled (!asynchronous_CAT);
  ui_->CAT_poll_interval_spin_box->setEnabled (!asynchronous_CAT);

  auto port_type = transceiver_factory_.CAT_port_type (rig);

  bool is_serial_CAT (TransceiverFactory::Capabilities::serial == port_type);
  auto const& cat_port = ui_->CAT_port_combo_box->currentText ();

  // only enable CAT option if transceiver has CAT PTT
  ui_->PTT_CAT_radio_button->setEnabled (CAT_PTT_enabled);
  ui_->PTT_VOX_radio_button->setEnabled (!is_tci_);
  ui_->PTT_DTR_radio_button->setEnabled (!is_tci_);

  auto enable_ptt_port = TransceiverFactory::PTT_method_CAT != ptt_method && TransceiverFactory::PTT_method_VOX != ptt_method;
  ui_->PTT_port_combo_box->setEnabled (enable_ptt_port);
  ui_->PTT_port_label->setEnabled (enable_ptt_port);

  if (CAT_indirect_serial_PTT)
    {
      ui_->PTT_port_combo_box->setItemData (ui_->PTT_port_combo_box->findText ("CAT")
                                            , combo_box_item_enabled, Qt::UserRole - 1);
    }
  else
    {
      ui_->PTT_port_combo_box->setItemData (ui_->PTT_port_combo_box->findText ("CAT")
                                            , combo_box_item_disabled, Qt::UserRole - 1);
      if ("CAT" == ui_->PTT_port_combo_box->currentText () && ui_->PTT_port_combo_box->currentIndex () > 0)
        {
          ui_->PTT_port_combo_box->setCurrentIndex (ui_->PTT_port_combo_box->currentIndex () - 1);
        }
    }
  ui_->PTT_RTS_radio_button->setEnabled (!((is_serial_CAT && ptt_port == cat_port && is_hw_handshake) || is_tci_));

  if (TransceiverFactory::basic_transceiver_name_ == rig)
    {
      // makes no sense with rig as "None"
      ui_->monitor_last_used_check_box->setEnabled (false);

      ui_->CAT_control_group_box->setEnabled (false);
      ui_->test_CAT_push_button->setEnabled (false);
      ui_->test_PTT_push_button->setEnabled (TransceiverFactory::PTT_method_DTR == ptt_method
                                             || TransceiverFactory::PTT_method_RTS == ptt_method);
      ui_->TX_audio_source_group_box->setEnabled (false);
      ui_->PWR_and_SWR_check_box->setChecked (false);
      ui_->PWR_and_SWR_check_box->setEnabled (false);
      ui_->check_SWR_check_box->setChecked (false);
      ui_->check_SWR_check_box->setEnabled (false);
    }
  else
    {
      ui_->monitor_last_used_check_box->setEnabled (true);
      ui_->CAT_control_group_box->setEnabled (true);
      if(!ui_->rig_combo_box->currentText().startsWith("OmniRig") && !ui_->rig_combo_box->currentText().startsWith("DX Lab") &&
         !ui_->rig_combo_box->currentText().startsWith("Ham Radio") && !ui_->rig_combo_box->currentText().startsWith("Kenwood TS-480") &&
         !ui_->rig_combo_box->currentText().startsWith("Kenwood TS-850") &&
         !ui_->rig_combo_box->currentText().startsWith("Kenwood TS-870")) {
         ui_->PWR_and_SWR_check_box->setEnabled (true);
      }
      ui_->test_CAT_push_button->setEnabled (true);
      ui_->test_PTT_push_button->setEnabled (false);
      ui_->TX_audio_source_group_box->setEnabled (transceiver_factory_.has_CAT_PTT_mic_data (rig) && TransceiverFactory::PTT_method_CAT == ptt_method);
      if (port_type != last_port_type_)
        {
          last_port_type_ = port_type;
          switch (port_type)
            {
            case TransceiverFactory::Capabilities::serial:
              fill_port_combo_box (ui_->CAT_port_combo_box);
              ui_->CAT_port_combo_box->setCurrentText (rig_params_.serial_port);
              if (ui_->CAT_port_combo_box->currentText ().isEmpty () && ui_->CAT_port_combo_box->count ())
                {
                  ui_->CAT_port_combo_box->setCurrentText (ui_->CAT_port_combo_box->itemText (0));
                }
              ui_->CAT_port_label->setText (tr ("Serial Port:"));
              ui_->CAT_port_combo_box->setToolTip (tr ("Serial port used for CAT control"));
              ui_->CAT_port_combo_box->setEnabled (true);
              break;

            case TransceiverFactory::Capabilities::tci:
              ui_->CAT_port_combo_box->clear ();
              ui_->CAT_port_combo_box->setCurrentText (rig_params_.tci_port);
              ui_->CAT_port_label->setText (tr ("TCI Server:"));
              ui_->CAT_port_combo_box->setToolTip (tr ("Optional hostname and port of TCI service.\n"
                                                     "Leave blank for a sensible default on this machine.\n"
                                                     "Formats:\n"
                                                     "\thostname:port\n"
                                                     "\tIPv4-address:port\n"
                                                     "\t[IPv6-address]:port"));
              ui_->CAT_port_combo_box->setEnabled (true);
              break;

            case TransceiverFactory::Capabilities::network:
              ui_->CAT_port_combo_box->clear ();
              ui_->CAT_port_combo_box->setCurrentText (rig_params_.network_port);
              ui_->CAT_port_label->setText (tr ("Network Server:"));
              ui_->CAT_port_combo_box->setToolTip (tr ("Optional hostname and port of network service.\n"
                                                       "Leave blank for a sensible default on this machine.\n"
                                                       "Formats:\n"
                                                       "\thostname:port\n"
                                                       "\tIPv4-address:port\n"
                                                       "\t[IPv6-address]:port"));
              ui_->CAT_port_combo_box->setEnabled (true);
              break;

            case TransceiverFactory::Capabilities::usb:
              ui_->CAT_port_combo_box->clear ();
              ui_->CAT_port_combo_box->setCurrentText (rig_params_.usb_port);
              ui_->CAT_port_label->setText (tr ("USB Device:"));
              ui_->CAT_port_combo_box->setToolTip (tr ("Optional device identification.\n"
                                                       "Leave blank for a sensible default for the rig.\n"
                                                       "Format:\n"
                                                       "\t[VID[:PID[:VENDOR[:PRODUCT]]]]"));
              ui_->CAT_port_combo_box->setEnabled (true);
              break;

            default:
              ui_->CAT_port_combo_box->clear ();
              ui_->CAT_port_combo_box->setEnabled (false);
              break;
            }
        }
      ui_->CAT_serial_port_parameters_group_box->setEnabled (is_serial_CAT);
      ui_->force_DTR_combo_box->setEnabled (is_serial_CAT
                                            && (cat_port != ptt_port
                                                || !ui_->PTT_DTR_radio_button->isEnabled ()
                                                || !ui_->PTT_DTR_radio_button->isChecked ()));
      ui_->force_RTS_combo_box->setEnabled (is_serial_CAT
                                            && !is_hw_handshake
                                            && (cat_port != ptt_port
                                                || !ui_->PTT_RTS_radio_button->isEnabled ()
                                                || !ui_->PTT_RTS_radio_button->isChecked ()));
    }
  ui_->mode_group_box->setEnabled (WSJT_RIG_NONE_CAN_SPLIT
                                   || TransceiverFactory::basic_transceiver_name_ != rig);
  ui_->split_operation_group_box->setEnabled (WSJT_RIG_NONE_CAN_SPLIT
                                              || TransceiverFactory::basic_transceiver_name_ != rig);
}

bool Configuration::impl::validate ()
{
  if (ui_->sound_input_combo_box->currentIndex () < 0
      && next_audio_input_device_.isNull ())
    {
      find_tab (ui_->sound_input_combo_box);
      MessageBox::critical_message (this, tr ("Invalid audio input device"));
      return false;
    }

  if (ui_->sound_input_channel_combo_box->currentIndex () < 0
      && next_audio_input_device_.isNull ())
    {
      find_tab (ui_->sound_input_combo_box);
      MessageBox::critical_message (this, tr ("Invalid audio input device"));
      return false;
    }

  if (ui_->sound_output_combo_box->currentIndex () < 0
      && next_audio_output_device_.isNull ())
    {
      find_tab (ui_->sound_output_combo_box);
      MessageBox::information_message (this, tr ("Invalid audio output device"));
      // don't reject as we can work without an audio output
    }

  if (!ui_->PTT_method_button_group->checkedButton ()->isEnabled ())
    {
      MessageBox::critical_message (this, tr ("Invalid PTT method"));
      return false;
    }

  auto ptt_method = static_cast<TransceiverFactory::PTTMethod> (ui_->PTT_method_button_group->checkedId ());
  auto ptt_port = ui_->PTT_port_combo_box->currentText ();
  if ((TransceiverFactory::PTT_method_DTR == ptt_method || TransceiverFactory::PTT_method_RTS == ptt_method)
      && (ptt_port.isEmpty ()
          || combo_box_item_disabled == ui_->PTT_port_combo_box->itemData (ui_->PTT_port_combo_box->findText (ptt_port), Qt::UserRole - 1)))
    {
      MessageBox::critical_message (this, tr ("Invalid PTT port"));
      return false;
    }

  if (ui_->rbField_Day->isEnabled () && ui_->rbField_Day->isChecked () &&
      !ui_->Field_Day_Exchange->hasAcceptableInput ())
    {
      find_tab (ui_->Field_Day_Exchange);
      MessageBox::critical_message (this, tr ("Invalid Contest Exchange")
                                    , tr ("You must input a valid ARRL Field Day exchange"));
      return false;
    }

  if (ui_->rbRTTY_Roundup->isEnabled () && ui_->rbRTTY_Roundup->isChecked () &&
      !ui_->RTTY_Exchange->hasAcceptableInput ())
    {
      find_tab (ui_->RTTY_Exchange);
      MessageBox::critical_message (this, tr ("Invalid Contest Exchange")
                                    , tr ("You must input a valid ARRL RTTY Roundup exchange"));
      return false;
    }

  if (dns_lookup_id_ > -1)
    {
      MessageBox::information_message (this, tr ("Pending DNS lookup, please try again later"));
      return false;
    }

  return true;
}

int Configuration::impl::exec ()
{
  // macros can be modified in the main window
  next_macros_.setStringList (macros_.stringList ());

  have_rig_ = rig_active_;	// record that we started with a rig open
  saved_rig_params_ = rig_params_; // used to detect changes that
                                   // require the Transceiver to be
                                   // re-opened
  rig_changed_ = false;

  initialize_models ();

  return QDialog::exec();
}

TransceiverFactory::ParameterPack Configuration::impl::gather_rig_data ()
{
  TransceiverFactory::ParameterPack result;
  result.rig_name = ui_->rig_combo_box->currentText ();

  switch (transceiver_factory_.CAT_port_type (result.rig_name))
    {
    case TransceiverFactory::Capabilities::tci:
      result.tci_port = ui_->CAT_port_combo_box->currentText ();
      result.network_port = rig_params_.network_port;
      result.usb_port = rig_params_.usb_port;
      result.serial_port = rig_params_.serial_port;
      break;

    case TransceiverFactory::Capabilities::network:
      result.network_port = ui_->CAT_port_combo_box->currentText ();
      result.tci_port = rig_params_.tci_port;
      result.usb_port = rig_params_.usb_port;
      result.serial_port = rig_params_.serial_port;
      break;

    case TransceiverFactory::Capabilities::usb:
      result.usb_port = ui_->CAT_port_combo_box->currentText ();
      result.tci_port = rig_params_.tci_port;
      result.network_port = rig_params_.network_port;
      result.serial_port = rig_params_.serial_port;
      break;

    default:
      result.serial_port = ui_->CAT_port_combo_box->currentText ();
      result.tci_port = rig_params_.tci_port;
      result.network_port = rig_params_.network_port;
      result.usb_port = rig_params_.usb_port;
      break;
    }

  result.baud = ui_->CAT_serial_baud_combo_box->currentText ().toInt ();
  result.data_bits = static_cast<TransceiverFactory::DataBits> (ui_->CAT_data_bits_button_group->checkedId ());
  result.stop_bits = static_cast<TransceiverFactory::StopBits> (ui_->CAT_stop_bits_button_group->checkedId ());
  result.handshake = static_cast<TransceiverFactory::Handshake> (ui_->CAT_handshake_button_group->checkedId ());
  result.force_dtr = ui_->force_DTR_combo_box->isEnabled () && ui_->force_DTR_combo_box->currentIndex () > 0;
  result.dtr_high = ui_->force_DTR_combo_box->isEnabled () && 1 == ui_->force_DTR_combo_box->currentIndex ();
  result.force_rts = ui_->force_RTS_combo_box->isEnabled () && ui_->force_RTS_combo_box->currentIndex () > 0;
  result.rts_high = ui_->force_RTS_combo_box->isEnabled () && 1 == ui_->force_RTS_combo_box->currentIndex ();
  result.poll_interval = ui_->CAT_poll_interval_spin_box->value ();
  if (ui_->PWR_and_SWR_check_box->isChecked ()) result.poll_interval |= do__pwr;
  if (is_tci_ && ui_->tci_audio_check_box->isChecked ()) result.poll_interval |= tci__audio;
  result.ptt_type = static_cast<TransceiverFactory::PTTMethod> (ui_->PTT_method_button_group->checkedId ());
  result.ptt_port = ui_->PTT_port_combo_box->currentText ();
  result.audio_source = static_cast<TransceiverFactory::TXAudioSource> (ui_->TX_audio_source_button_group->checkedId ());
  result.split_mode = static_cast<TransceiverFactory::SplitMode> (ui_->split_mode_button_group->checkedId ());
  return result;
}

void Configuration::impl::accept ()
{
  // Called when OK button is clicked.
  if (!validate ())
    {
      return;			// not accepting
    }

  // extract all rig related configuration parameters into temporary
  // structure for checking if the rig needs re-opening without
  // actually updating our live state
  auto temp_rig_params = gather_rig_data ();

  // open_rig() uses values from models so we use it to validate the
  // Transceiver settings before agreeing to accept the configuration
  if (temp_rig_params != rig_params_ && !open_rig ())
    {
      return;			// not accepting
    }

  QDialog::accept();            // do this before accessing custom
                                // models so that any changes in
                                // delegates in views get flushed to
                                // the underlying models before we
                                // access them

  sync_transceiver (true);	// force an update

  //
  // from here on we are bound to accept the new configuration
  // parameters so extract values from models and make them live
  //

  if (next_font_ != font_)
    {
      font_ = next_font_;
      Q_EMIT self_->text_font_changed (font_);
    }

  if (next_decoded_text_font_ != decoded_text_font_)
    {
      decoded_text_font_ = next_decoded_text_font_;
      next_decode_highlighing_model_.set_font (decoded_text_font_);
      ui_->highlighting_list_view->reset ();
      Q_EMIT self_->decoded_text_font_changed (decoded_text_font_);
    }

  rig_params_ = temp_rig_params; // now we can go live with the rig
                                 // related configuration parameters
  rig_is_dummy_ = TransceiverFactory::basic_transceiver_name_ == rig_params_.rig_name;
  is_tci_ = rig_params_.rig_name.startsWith("TCI Cli");
  // Check to see whether SoundInThread must be restarted,
  // and save user parameters.
  {
    auto const& selected_device = ui_->sound_input_combo_box->currentData ().value<audio_info_type> ().first;
    if (selected_device != next_audio_input_device_)
      {
        next_audio_input_device_ = selected_device;
      }
  }

  {
    auto const& selected_device = ui_->sound_output_combo_box->currentData ().value<audio_info_type> ().first;
    if (selected_device != next_audio_output_device_)
      {
        next_audio_output_device_ = selected_device;
      }
  }

  if (next_audio_input_channel_ != static_cast<AudioDevice::Channel> (ui_->sound_input_channel_combo_box->currentIndex ()))
    {
      next_audio_input_channel_ = static_cast<AudioDevice::Channel> (ui_->sound_input_channel_combo_box->currentIndex ());
    }
  Q_ASSERT (next_audio_input_channel_ <= AudioDevice::Right);

  if (next_audio_output_channel_ != static_cast<AudioDevice::Channel> (ui_->sound_output_channel_combo_box->currentIndex ()))
    {
      next_audio_output_channel_ = static_cast<AudioDevice::Channel> (ui_->sound_output_channel_combo_box->currentIndex ());
    }
  Q_ASSERT (next_audio_output_channel_ <= AudioDevice::Both);

  if (audio_input_device_ != next_audio_input_device_ || next_audio_input_device_.isNull ())
    {
      audio_input_device_ = next_audio_input_device_;
      restart_sound_input_device_ = true;
    }
  if (audio_input_channel_ != next_audio_input_channel_)
    {
      audio_input_channel_ = next_audio_input_channel_;
      restart_sound_input_device_ = true;
    }
  if (audio_output_device_ != next_audio_output_device_ || next_audio_output_device_.isNull ())
    {
      audio_output_device_ = next_audio_output_device_;
      restart_sound_output_device_ = true;
    }
  if (audio_output_channel_ != next_audio_output_channel_)
    {
      audio_output_channel_ = next_audio_output_channel_;
      restart_sound_output_device_ = true;
    }
  // qDebug () << "Configure::accept: audio i/p:" << audio_input_device_.deviceName ()
  //           << "chan:" << audio_input_channel_
  //           << "o/p:" << audio_output_device_.deviceName ()
  //           << "chan:" << audio_output_channel_
  //           << "reset i/p:" << restart_sound_input_device_
  //           << "reset o/p:" << restart_sound_output_device_;

  my_callsign_ = ui_->callsign_line_edit->text ();
  my_grid_ = ui_->grid_line_edit->text ();
  FD_exchange_= ui_->Field_Day_Exchange->text ().toUpper ();
  RTTY_exchange_= ui_->RTTY_Exchange->text ().toUpper ();
  Contest_Name_= ui_->Contest_Name->text ().toUpper ();
  Blacklist1_= ui_->Blacklist1->text ().toUpper ();
  Blacklist2_= ui_->Blacklist2->text ().toUpper ();
  Blacklist3_= ui_->Blacklist3->text ().toUpper ();
  Blacklist4_= ui_->Blacklist4->text ().toUpper ();
  Blacklist5_= ui_->Blacklist5->text ().toUpper ();
  Blacklist6_= ui_->Blacklist6->text ().toUpper ();
  Blacklist7_= ui_->Blacklist7->text ().toUpper ();
  Blacklist8_= ui_->Blacklist8->text ().toUpper ();
  Blacklist9_= ui_->Blacklist9->text ().toUpper ();
  Blacklist10_= ui_->Blacklist10->text ().toUpper ();
  Blacklist11_= ui_->Blacklist11->text ().toUpper ();
  Blacklist12_= ui_->Blacklist12->text ().toUpper ();
  Whitelist1_= ui_->Whitelist1->text ().toUpper ();
  Whitelist2_= ui_->Whitelist2->text ().toUpper ();
  Whitelist3_= ui_->Whitelist3->text ().toUpper ();
  Whitelist4_= ui_->Whitelist4->text ().toUpper ();
  Whitelist5_= ui_->Whitelist5->text ().toUpper ();
  Whitelist6_= ui_->Whitelist6->text ().toUpper ();
  Whitelist7_= ui_->Whitelist7->text ().toUpper ();
  Whitelist8_= ui_->Whitelist8->text ().toUpper ();
  Whitelist9_= ui_->Whitelist9->text ().toUpper ();
  Whitelist10_= ui_->Whitelist10->text ().toUpper ();
  Whitelist11_= ui_->Whitelist11->text ().toUpper ();
  Whitelist12_= ui_->Whitelist12->text ().toUpper ();
  Pass1_= ui_->Pass1->text ().toUpper ();
  Pass2_= ui_->Pass2->text ().toUpper ();
  Pass3_= ui_->Pass3->text ().toUpper ();
  Pass4_= ui_->Pass4->text ().toUpper ();
  Pass5_= ui_->Pass5->text ().toUpper ();
  Pass6_= ui_->Pass6->text ().toUpper ();
  Pass7_= ui_->Pass7->text ().toUpper ();
  Pass8_= ui_->Pass8->text ().toUpper ();
  Pass9_= ui_->Pass9->text ().toUpper ();
  Pass10_= ui_->Pass10->text ().toUpper ();
  Pass11_= ui_->Pass11->text ().toUpper ();
  Pass12_= ui_->Pass12->text ().toUpper ();
  Territory1_= ui_->Territory1->text ();
  Territory2_= ui_->Territory2->text ();
  Territory3_= ui_->Territory3->text ();
  Territory4_= ui_->Territory4->text ();
  highlight_orange_callsigns_= ui_-> highlight_orange_callsigns->text ().toUpper ();
  highlight_blue_callsigns_= ui_-> highlight_blue_callsigns->text ().toUpper ();
  PWR_and_SWR_ = ui_->PWR_and_SWR_check_box->isChecked ();
  check_SWR_ = ui_->check_SWR_check_box->isChecked ();

  spot_to_psk_reporter_ = ui_->psk_reporter_check_box->isChecked ();
  psk_reporter_tcpip_ = ui_->psk_reporter_tcpip_check_box->isChecked ();
  id_interval_ = ui_->CW_id_interval_spin_box->value ();
  align_steps_ = ui_->align_spin_box->value ();
  align_steps2_ = ui_->align_spin_box2->value ();
  ntrials_ = ui_->sbNtrials->value ();
  volume_ = ui_->TCI_spin_box->value ();
  txDelay_ = ui_->sbTxDelay->value ();
  aggressive_ = ui_->sbAggressive->value ();
  degrade_ = ui_->sbDegrade->value ();
  RxBandwidth_ = ui_->sbBandwidth->value ();
  tci_audio_ = ui_->tci_audio_check_box->isChecked ();
  id_after_73_ = ui_->CW_id_after_73_check_box->isChecked ();
  tx_QSY_allowed_ = ui_->tx_QSY_check_box->isChecked ();
  progressBar_red_ = ui_->progress_bar_check_box->isChecked ();
  monitor_off_at_startup_ = ui_->monitor_off_check_box->isChecked ();
  monitor_last_used_ = ui_->monitor_last_used_check_box->isChecked ();
  type_2_msg_gen_ = static_cast<Type2MsgGen> (ui_->type_2_msg_gen_combo_box->currentIndex ());
  log_as_RTTY_ = ui_->log_as_RTTY_check_box->isChecked ();
  report_in_comments_ = ui_->report_in_comments_check_box->isChecked ();
  specOp_in_comments_ = ui_->specOp_in_comments_check_box->isChecked ();
  prompt_to_log_ = ui_->prompt_to_log_check_box->isChecked ();
  autoLog_ = ui_->cbAutoLog->isChecked();
  contestingOnly_ = ui_->cbContestingOnly->isChecked();
  ZZ00_ = ui_->cbZZ00->isChecked ();
  log4digitGrids_ = ui_->cbLog4digitGrids->isChecked();
  decodes_from_top_ = ui_->decodes_from_top_check_box->isChecked ();
  insert_blank_ = ui_->insert_blank_check_box->isChecked ();
  detailed_blank_ = ui_->cb_detailed_blank_line->isChecked ();
  DXCC_ = ui_->DXCC_check_box->isChecked ();
  gridMap_= ui_->Map_Grid_to_State->isChecked ();
  gridMapAll_ = ui_->Map_All_Messages->isChecked();
  ppfx_ = ui_->ppfx_check_box->isChecked ();
  miles_ = ui_->miles_check_box->isChecked ();
  quick_call_ = ui_->quick_call_check_box->isChecked ();
  disable_TX_on_73_ = ui_->disable_TX_on_73_check_box->isChecked ();
  force_call_1st_ = ui_->force_call_1st_check_box->isChecked ();
  alternate_bindings_ = ui_->alternate_bindings_check_box->isChecked ();
  watchdog_ = ui_->tx_watchdog_spin_box->value ();
  tune_watchdog_ = ui_->tune_watchdog_check_box->isChecked ();
  tune_watchdog_time_ = ui_->tune_watchdog_spin_box->value ();
  TX_messages_ = ui_->TX_messages_check_box->isChecked ();
  data_mode_ = static_cast<DataMode> (ui_->TX_mode_button_group->checkedId ());
  bLowSidelobes_ = ui_->rbLowSidelobes->isChecked();
  save_directory_.setPath (ui_->save_path_display_label->text ());
  azel_directory_.setPath (ui_->azel_path_display_label->text ());
  enable_VHF_features_ = ui_->enable_VHF_features_check_box->isChecked ();
  decode_at_52s_ = ui_->decode_at_52s_check_box->isChecked ();
  kHz_without_k_ = ui_->kHz_without_k_check_box->isChecked ();
  button_coloring_disabled_ = ui_->disable_button_coloring_check_box->isChecked ();
  Wait_features_enabled_ = ui_->enable_Wait_features_check_box->isChecked ();
  showDistance_ = ui_->cb_showDistance->isChecked();
  showAzimuth_ = ui_->cb_showAzimuth->isChecked();
  align_ = ui_->cb_Align->isChecked();
  repeat_Tx_ = ui_->repeat_Tx_check_box->isChecked ();
  auto_astro_ = ui_->auto_astro_check_box->isChecked ();
  single_decode_ = ui_->single_decode_check_box->isChecked ();
  twoPass_ = ui_->cbTwoPass->isChecked ();
  highDPI_ = ui_->cbHighDPI->isChecked ();
  largerTabWidget_ = ui_->cbLargerTabWidget->isChecked ();
  bSuperFox_ = ui_->cbSuperFox->isChecked ();
  Individual_Contest_Name_ = ui_->cbContestName->isChecked ();
  NCCC_Sprint_ = ui_->cb_NCCC_Sprint->isChecked ();
  Blacklisted_ = ui_->cbBlacklist->isChecked ();
  Whitelisted_ = ui_->cbWhitelist->isChecked ();
  AlwaysPass_ = ui_->cbPass->isChecked ();
  filters_for_Wait_and_Pounce_only_ = ui_->cb_filters_for_Wait_and_Pounce_only->isChecked ();
  filters_for_word2_ = ui_->cb_filters_for_word2->isChecked ();
  twoDays_ = ui_->cb_twoDays->isChecked ();
  bSpecialOp_ = ui_->gbSpecialOpActivity->isChecked ();
  bCloudLog_ = ui_->gbCloudlog->isChecked ();
  cloudLogApiUrl_ = ui_->leCloudlogApiUrl->text ();
  cloudLogApiKey_ = ui_->leCloudlogApiKey->text ();
  cloudLogStationID_ = ui_->sbCloudlogStationID->value ();
  SelectedActivity_ = ui_->special_op_activity_button_group->checkedId();
  x2ToneSpacing_ = ui_->cbx2ToneSpacing->isChecked ();
  x4ToneSpacing_ = ui_->cbx4ToneSpacing->isChecked ();
  calibration_.intercept = ui_->calibration_intercept_spin_box->value ();
  calibration_.slope_ppm = ui_->calibration_slope_ppm_spin_box->value ();
  sortAlphabetically_ = ui_->cbSortAlphabetically->isChecked ();
  hideCARD_ = ui_->cbHideCARD->isChecked ();
  AzElExtraLines_ = ui_->checkBoxAzElExtraLines->isChecked ();
  pwrBandTxMemory_ = ui_->checkBoxPwrBandTxMemory->isChecked ();
  pwrBandTuneMemory_ = ui_->checkBoxPwrBandTuneMemory->isChecked ();
  opCall_=ui_->opCallEntry->text();
  OTPinterval_=ui_->sbOTPinterval->value();
  OTPSeed_=ui_->OTPSeed->text();
  OTPUrl_=ui_->OTPUrl->text();
  OTPEnabled_=ui_->cbOTP->isChecked();
  ShowOTP_=ui_->cbShowOTP->isChecked();

  auto new_server = ui_->udp_server_line_edit->text ().trimmed ();
  auto new_interfaces = get_selected_network_interfaces (ui_->udp_interfaces_combo_box);
  if (new_server != udp_server_name_ || new_interfaces != udp_interface_names_)
    {
      udp_server_name_ = new_server;
      udp_interface_names_ = new_interfaces;
      Q_EMIT self_->udp_server_changed (udp_server_name_, udp_interface_names_);
    }

  auto new_port = ui_->udp_server_port_spin_box->value ();
  if (new_port != udp_server_port_)
    {
      udp_server_port_ = new_port;
      Q_EMIT self_->udp_server_port_changed (udp_server_port_);
    }

  auto new_TTL = ui_->udp_TTL_spin_box->value ();
  if (new_TTL != udp_TTL_)
    {
      udp_TTL_ = new_TTL;
      Q_EMIT self_->udp_TTL_changed (udp_TTL_);
    }

  if (ui_->accept_udp_requests_check_box->isChecked () != accept_udp_requests_)
    {
      accept_udp_requests_ = ui_->accept_udp_requests_check_box->isChecked ();
      Q_EMIT self_->accept_udp_requests_changed (accept_udp_requests_);
    }

  n1mm_server_name_ = ui_->n1mm_server_name_line_edit->text ();
  n1mm_server_port_ = ui_->n1mm_server_port_spin_box->value ();
  broadcast_to_n1mm_ = ui_->enable_n1mm_broadcast_check_box->isChecked ();

  udpWindowToFront_ = ui_->udpWindowToFront->isChecked ();
  udpWindowRestore_ = ui_->udpWindowRestore->isChecked ();

  if (macros_.stringList () != next_macros_.stringList ())
    {
      macros_.setStringList (next_macros_.stringList ());
    }

  region_ = IARURegions::value (ui_->region_combo_box->currentText ());

  if (frequencies_.frequency_list () != next_frequencies_.frequency_list ())
    {
      frequencies_.frequency_list (next_frequencies_.frequency_list ());
      frequencies_.sort (FrequencyList_v2_101::frequency_column);
    }

  if (stations_.station_list () != next_stations_.station_list ())
    {
      stations_.station_list (next_stations_.station_list ());
      stations_.sort (StationList::band_column);
    }

  if (decode_highlighing_model_.items () != next_decode_highlighing_model_.items ())
    {
      decode_highlighing_model_.items (next_decode_highlighing_model_.items ());
      Q_EMIT self_->decode_highlighting_changed (decode_highlighing_model_);
    }
  highlight_by_mode_ = ui_->highlight_by_mode_check_box->isChecked ();
  highlight_only_fields_ = ui_->only_fields_check_box->isChecked ();
  include_WAE_entities_ = ui_->include_WAE_check_box->isChecked ();
  highlight_73_ = ui_->highlight_73_check_box->isChecked ();
  highlight_orange_ = ui_->highlight_orange_check_box->isChecked ();
  highlight_blue_ = ui_->highlight_blue_check_box->isChecked ();
  alternate_erase_button_ = ui_->alternate_erase_button_check_box->isChecked ();
  show_country_names_ = ui_->show_country_names_check_box->isChecked ();
  LotW_days_since_upload_ = ui_->LotW_days_since_upload_spin_box->value ();
  lotw_users_.set_age_constraint (LotW_days_since_upload_);

  if (ui_->use_dynamic_grid->isChecked() && !use_dynamic_grid_ )
  {
    // turning on so clear it so only the next location update gets used
    dynamic_grid_.clear ();
  }
  use_dynamic_grid_ = ui_->use_dynamic_grid->isChecked();
  highlight_DXcall_ = ui_->cbHighlightDXcall->isChecked();
  clear_DXcall_ = ui_->cbClearDXcall->isChecked();
  highlight_DXgrid_ = ui_->cbHighlightDXgrid->isChecked();
  clear_DXgrid_ = ui_->cbClearDXgrid->isChecked();
  erase_BandActivity_ = ui_->cbEraseBandActivity->isChecked();
  set_RXtoTX_ = ui_->cbRxToTxAfterQSO->isChecked();
  ZZ00_ = ui_->cbZZ00->isChecked();
  NCCC_Sprint_ = ui_->cb_NCCC_Sprint->isChecked();
  Blacklisted_ = ui_->cbBlacklist->isChecked();
  Whitelisted_ = ui_->cbWhitelist->isChecked();
  AlwaysPass_ = ui_->cbPass->isChecked();
  filters_for_Wait_and_Pounce_only_ = ui_->cb_filters_for_Wait_and_Pounce_only->isChecked();
  filters_for_word2_ = ui_->cb_filters_for_word2->isChecked();
  twoDays_ = ui_->cb_twoDays->isChecked();
  alert_CQ_ = ui_->cbCQ->isChecked();
  alert_MyCall_ = ui_->cbMyCall->isChecked();
  alert_DXCC_ = ui_->cbDXCC->isChecked();
  alert_DXCCOB_ = ui_->cbDXCCOB->isChecked();
  alert_Grid_ = ui_->cbGrid->isChecked();
  alert_GridOB_ = ui_->cbGridOB->isChecked();
  alert_Continent_ = ui_->cbContinent->isChecked();
  alert_ContinentOB_ = ui_->cbContinentOB->isChecked();
  alert_CQZ_ = ui_->cbCQZ->isChecked();
  alert_CQZOB_ = ui_->cbCQZOB->isChecked();
  alert_ITUZ_ = ui_->cbITUZ->isChecked();
  alert_ITUZOB_ = ui_->cbITUZOB->isChecked();
  alert_DXcall_ = ui_->cbDXcall->isChecked();
  alert_QSYmessage_ = ui_->cbQSYmessage->isChecked();
  alert_Enabled_ = ui_->pbAlerts->isChecked();

  write_settings ();		// make visible to all
}

void Configuration::impl::reject ()
{
  if (dns_lookup_id_ > -1)
    {
      QHostInfo::abortHostLookup (dns_lookup_id_);
      dns_lookup_id_ = -1;
    }

  initialize_models ();		// reverts to settings as at exec ()

  // check if the Transceiver instance changed, in which case we need
  // to re open any prior Transceiver type
  if (rig_changed_)
    {
      if (have_rig_)
        {
          // we have to do this since the rig has been opened since we
          // were exec'ed even though it might fail
          open_rig ();
        }
      else
        {
          close_rig ();
        }
    }

  // qDebug () << "Configure::reject: audio i/p:" << audio_input_device_.deviceName ()
  //           << "chan:" << audio_input_channel_
  //           << "o/p:" << audio_output_device_.deviceName ()
  //           << "chan:" << audio_output_channel_
  //           << "reset i/p:" << restart_sound_input_device_
  //           << "reset o/p:" << restart_sound_output_device_;

  QDialog::reject ();
}

void Configuration::impl::on_font_push_button_clicked ()
{
  next_font_ = QFontDialog::getFont (0, next_font_, this);
}

void Configuration::impl::on_reset_highlighting_to_defaults_push_button_clicked (bool /*checked*/)
{
  if (MessageBox::Yes == MessageBox::query_message (this
                                                    , tr ("Reset Decode Highlighting")
                                                    , tr ("Reset all decode highlighting and priorities to default values")))
    {
      next_decode_highlighing_model_.items (DecodeHighlightingModel::default_items ());
    }
}

void Configuration::impl::on_reset_highlighting_to_defaults2_push_button_clicked (bool /*checked*/)
{
    if (MessageBox::Yes == MessageBox::query_message (this
                             , tr ("Reset Decode Highlighting")
                             , tr ("Reset all decode highlighting and priorities to default values")))
    {
      next_decode_highlighing_model_.items (DecodeHighlightingModel::default_items2 ());
    }
}

void Configuration::impl::on_rescan_log_push_button_clicked (bool /*clicked*/)
{
  if (logbook_) {
    logbook_->rescan ();
  }
}

void Configuration::impl::on_CTY_download_button_clicked (bool /*clicked*/)
{
  ui_->CTY_download_button->setEnabled (false); // disable button until download is complete
  QDir dataPath {QStandardPaths::writableLocation (QStandardPaths::DataLocation)};
  cty_download.configure(network_manager_,
                         "http://www.country-files.com/bigcty/cty.dat",
                         dataPath.absoluteFilePath("cty.dat"),
                         "WSJT-X CTY Downloader");

  // set up LoTW users CSV file fetching
  connect (&cty_download, &FileDownload::complete, this, &Configuration::impl::after_CTY_downloaded, Qt::UniqueConnection);
  connect (&cty_download, &FileDownload::error, this, &Configuration::impl::error_during_CTY_download, Qt::UniqueConnection);
  cty_download.start_download();
}

void Configuration::impl::set_CTY_DAT_version(QString const& version)
{
  ui_->CTY_file_label->setText(QString{"CTY File Version: %1"}.arg(version));
}

void Configuration::impl::error_during_CTY_download (QString const& reason)
{
  MessageBox::warning_message (this, tr ("Error Loading CTY.DAT"), reason);
  after_CTY_downloaded();
}

void Configuration::impl::after_CTY_downloaded ()
{
  ui_->CTY_download_button->setEnabled (true);
  if (logbook_) {
    logbook_->rescan ();
    ui_->CTY_file_label->setText(QString{"CTY File Version: %1"}.arg(logbook_->cty_version()));
  }
}

void Configuration::impl::on_CALL3_download_button_clicked (bool /*clicked*/)
{
  ui_->CALL3_download_button->setEnabled (false); // disable button until download is complete
  QDir dataPath {QStandardPaths::writableLocation (QStandardPaths::DataLocation)};
  QFile g {dataPath.absolutePath() + "/" + "CALL3_backup.TXT"};
  if (g.exists()) QFile::rename(dataPath.absolutePath() + "/" + "CALL3_backup.TXT", dataPath.absolutePath() + "/" + "CALL3_backup.tmp");
  QFile f {dataPath.absolutePath() + "/" + "CALL3.TXT"};
  if (f.exists()) QFile::rename(dataPath.absolutePath() + "/" + "CALL3.TXT", dataPath.absolutePath() + "/" + "CALL3_backup.TXT");
  cty_download.configure(network_manager_,
                         "https://wsjt-x-improved.sourceforge.io/CALL3.TXT",
                         dataPath.absoluteFilePath("CALL3.TXT"),
                         "Downloading latest CALL3.TXT file");

  // set up CALL3.TXT file fetching
  connect (&cty_download, &FileDownload::complete, this, &Configuration::impl::after_CALL3_downloaded, Qt::UniqueConnection);
  connect (&cty_download, &FileDownload::error, this, &Configuration::impl::error_during_CALL3_download, Qt::UniqueConnection);
  cty_download.start_download();
  ui_->CALL3_file_label->setText("Downloading ...");
}

void Configuration::impl::on_CALL3_EME_download_button_clicked (bool /*clicked*/)
{
  ui_->CALL3_EME_download_button->setEnabled (false); // disable button until download is complete
  QDir dataPath {QStandardPaths::writableLocation (QStandardPaths::DataLocation)};
  QFile g {dataPath.absolutePath() + "/" + "CALL3_backup.TXT"};
  if (g.exists()) QFile::rename(dataPath.absolutePath() + "/" + "CALL3_backup.TXT", dataPath.absolutePath() + "/" + "CALL3_backup.tmp");
  QFile f {dataPath.absolutePath() + "/" + "CALL3.TXT"};
  if (f.exists()) QFile::rename(dataPath.absolutePath() + "/" + "CALL3.TXT", dataPath.absolutePath() + "/" + "CALL3_backup.TXT");
  cty_download.configure(network_manager_,
                         "https://wsjt-x-improved.sourceforge.io/CALL3_EME.TXT",
                         dataPath.absoluteFilePath("CALL3.TXT"),
                         "Downloading latest CALL3.TXT file");

  // set up CALL3.TXT file fetching
  connect (&cty_download, &FileDownload::complete, this, &Configuration::impl::after_CALL3_downloaded, Qt::UniqueConnection);
  connect (&cty_download, &FileDownload::error, this, &Configuration::impl::error_during_CALL3_download, Qt::UniqueConnection);
  cty_download.start_download();
  ui_->CALL3_file_label->setText("Downloading ...");
}

void Configuration::impl::error_during_CALL3_download (QString const& reason)
{
  MessageBox::warning_message (this, tr ("Error Loading CALL3.TXT file"), reason);
  ui_->CALL3_download_button->setEnabled (true);
  ui_->CALL3_EME_download_button->setEnabled (true);
  QDir dataPath {QStandardPaths::writableLocation (QStandardPaths::DataLocation)};
  QFile f {dataPath.absolutePath() + "/" + "CALL3.TXT"};
  if (!f.exists()) QFile::copy(dataPath.absolutePath() + "/" + "CALL3_backup.TXT", dataPath.absolutePath() + "/" + "CALL3.TXT");
  QFile g {dataPath.absolutePath() + "/" + "CALL3_backup.TXT"};
  QFile h {dataPath.absolutePath() + "/" + "CALL3_backup.tmp"};
  if (!g.exists() and h.exists()) {
    QFile::rename(dataPath.absolutePath() + "/" + "CALL3_backup.tmp", dataPath.absolutePath() + "/" + "CALL3_backup.TXT");
  } else {
    if (h.exists()) QFile::remove(dataPath.absolutePath() + "/" + "CALL3_backup.tmp");
  }
  read_CALL3_version ();
}

void Configuration::impl::after_CALL3_downloaded ()
{
  ui_->CALL3_download_button->setEnabled (true);
  ui_->CALL3_EME_download_button->setEnabled (true);
  QDir dataPath {QStandardPaths::writableLocation (QStandardPaths::DataLocation)};
  QFile g {dataPath.absolutePath() + "/" + "CALL3_backup.TXT"};
  QFile h {dataPath.absolutePath() + "/" + "CALL3_backup.tmp"};
  if (!g.exists() and h.exists()) {
    QFile::rename(dataPath.absolutePath() + "/" + "CALL3_backup.tmp", dataPath.absolutePath() + "/" + "CALL3_backup.TXT");
  } else {
    if (h.exists()) QFile::remove(dataPath.absolutePath() + "/" + "CALL3_backup.tmp");
  }
  read_CALL3_version ();
}

void Configuration::impl::read_CALL3_version ()
{
  QString text;
  QDir dataPath {QStandardPaths::writableLocation (QStandardPaths::DataLocation)};
  QFile call3file {dataPath.absolutePath() + "/" + "CALL3.TXT"};
    QTextStream call3stream(&call3file);
    if(call3file.open (QIODevice::ReadOnly | QIODevice::Text)) {
        while (!call3stream.atEnd()) {
            text = call3stream.readLine();
            if (text.contains("// Version:")) break;
        }
        call3stream.flush();
        call3file.close();
    }
  if (text.contains("// Version:")) {
    ui_->CALL3_file_label->setText("CALL3 File Version:" + text.mid(11,30));
  } else {
    ui_->CALL3_file_label->setText("CALL3 File Version: not available");
  }
}

void Configuration::impl::on_LotW_CSV_fetch_push_button_clicked (bool /*checked*/)
{
  lotw_users_.load (ui_->LotW_CSV_URL_line_edit->text (), true, true);
  ui_->LotW_CSV_fetch_push_button->setEnabled (false);
}

void Configuration::impl::on_decoded_text_font_push_button_clicked ()
{
  next_decoded_text_font_ = QFontDialog::getFont (0, decoded_text_font_ , this
                                                  , tr ("WSJT-X Decoded Text Font Chooser")
                                                  , QFontDialog::MonospacedFonts
                                                  );
}

void Configuration::impl::on_hamlib_download_button_clicked (bool /*clicked*/)
{
#ifdef WIN32
  extern char* hamlib_version2;
  QString hamlib = QString(QLatin1String(hamlib_version2));
  SettingsGroup g {settings_, "Configuration"};
  settings_->setValue ("HamlibBackedUp", hamlib);
  settings_->sync ();
  QDir dataPath = QCoreApplication::applicationDirPath();
  QFile f1 {dataPath.absolutePath() + "/" + "libhamlib-4_old.dll"};
  QFile f2 {dataPath.absolutePath() + "/" + "libhamlib-4_new.dll"};
  if (f1.exists()) f1.remove();
  if (f2.exists()) f2.remove();
  ui_->hamlib_download_button->setEnabled (false);
  ui_->revert_update_button->setEnabled (false);
  if (ui_->rbHamlib32->isChecked()) {
    cty_download.configure(network_manager_,
//                           "https://n0nb.users.sourceforge.net/dll32/libhamlib-4.dll",
                           "http://dr-risse-consulting.de/hamlib/dll32/libhamlib-4.dll",  // hamlib mirror DG2YCB
                           dataPath.absoluteFilePath("libhamlib-4_new.dll"),
                           "Downloading latest libhamlib-4.dll");
  } else {
    cty_download.configure(network_manager_,
//                           "https://n0nb.users.sourceforge.net/dll64/libhamlib-4.dll",
                           "http://dr-risse-consulting.de/hamlib/dll64/libhamlib-4.dll",  // hamlib mirror DG2YCB
                           dataPath.absoluteFilePath("libhamlib-4_new.dll"),
                           "Downloading latest libhamlib-4.dll");
  }
  connect (&cty_download, &FileDownload::complete, this, &Configuration::impl::after_hamlib_downloaded, Qt::UniqueConnection);
  connect (&cty_download, &FileDownload::error, this, &Configuration::impl::error_during_hamlib_download, Qt::UniqueConnection);
  ui_->in_use->setText("Downloading ...");

  cty_download.start_download();
#else
  MessageBox::warning_message (this, tr ("Hamlib update only available on Windows."));
#endif
}

void Configuration::impl::error_during_hamlib_download (QString const& reason)
{
  QDir dataPath = QCoreApplication::applicationDirPath();
  MessageBox::warning_message (this, tr ("Error Loading libhamlib-4.dll"), reason);
  ui_->hamlib_download_button->setEnabled (true);
  ui_->revert_update_button->setEnabled (true);
#ifdef WIN32
  extern char* hamlib_version2;
  QString hamlib = QString(QLatin1String(hamlib_version2));
  ui_->in_use->setText(hamlib);
#else
  extern char* hamlib_version2;
  QString hamlib = QString(QLatin1String(hamlib_version2));
  ui_->in_use->setText(hamlib);
#endif
}

void Configuration::impl::after_hamlib_downloaded ()
{
  QDir dataPath = QCoreApplication::applicationDirPath();
  QFile::rename(dataPath.absolutePath() + "/" + "libhamlib-4.dll", dataPath.absolutePath() + "/" + "libhamlib-4_old.dll");
  QTimer::singleShot (1000, [=] {
    QFile::rename(dataPath.absolutePath() + "/" + "libhamlib-4_new.dll", dataPath.absolutePath() + "/" + "libhamlib-4.dll");
    ui_->in_use->setText("Download completed. Restart the program.");
  });
  QTimer::singleShot (1500, [=] {
    MessageBox::information_message (this, tr ("Hamlib Update successful \n\nNew Hamlib will be used after restart"));
    ui_->revert_update_button->setEnabled (true);
    ui_->hamlib_download_button->setEnabled (true);
  });
}

void Configuration::impl::on_revert_update_button_clicked (bool /*clicked*/)
{
#ifdef WIN32
  QDir dataPath = QCoreApplication::applicationDirPath();
  QFile f {dataPath.absolutePath() + "/" + "libhamlib-4_old.dll"};
  if (f.exists()) {
    ui_->revert_update_button->setEnabled (false);
    ui_->hamlib_download_button->setEnabled (false);
    QFile::rename(dataPath.absolutePath() + "/" + "libhamlib-4.dll", dataPath.absolutePath() + "/" + "libhamlib-4_new.dll");
    QTimer::singleShot (1000, [=] {
      QFile::copy(dataPath.absolutePath() + "/" + "libhamlib-4_old.dll", dataPath.absolutePath() + "/" + "libhamlib-4.dll");
    });
    QTimer::singleShot (2000, [=] {
      MessageBox::information_message (this, tr ("Hamlib successfully reverted \n\nReverted Hamlib will be used after restart"));
      ui_->revert_update_button->setEnabled (true);
      ui_->hamlib_download_button->setEnabled (true);
    });
  } else {
    MessageBox::warning_message (this, tr ("No Hamlib update found that could be reverted"));
  }
#else
  MessageBox::warning_message (this, tr ("Hamlib update only available on Windows."));
#endif
}

void Configuration::impl::display_file_information ()
{
#ifdef WIN32
  QDir dataPath = QCoreApplication::applicationDirPath();
  extern char* hamlib_version2;
  QString hamlib = QString(QLatin1String(hamlib_version2));
  ui_->in_use->setText(hamlib);
  QFileInfo fi2(dataPath.absolutePath() + "/" + "libhamlib-4_old.dll");
  QString birthTime2 = fi2.birthTime().toString("yyyy-MM-dd hh:mm");
  QFile f {dataPath.absolutePath() + "/" + "libhamlib-4_old.dll"};
  if (f.exists()) {
    if (hamlib_backed_up_=="") {
      ui_->backed_up->setText(QString{"no hamlib data available, file saved %1"}.arg(birthTime2));
    } else {
      ui_->backed_up->setText(hamlib_backed_up_);
    }
  } else {
      ui_->backed_up->setText("");
  }
#else
  extern char* hamlib_version2;
  QString hamlib = QString(QLatin1String(hamlib_version2));
  ui_->in_use->setText(hamlib);
#endif
}

void Configuration::impl::on_DXCC_check_box_clicked(bool checked)
{
    if (checked) {
        ui_->ppfx_check_box->setEnabled (true);
        ui_->show_country_names_check_box->setEnabled (true);
    } else {
        ui_->ppfx_check_box->setEnabled (false);
        ui_->show_country_names_check_box->setEnabled (false);
    }
}

void Configuration::impl::on_PTT_port_combo_box_activated (int /* index */)
{
  set_rig_invariants ();
}

void Configuration::impl::on_CAT_port_combo_box_activated (int /* index */)
{
  set_rig_invariants ();
}

void Configuration::impl::on_CAT_serial_baud_combo_box_currentIndexChanged (int /* index */)
{
  set_rig_invariants ();
}

void Configuration::impl::on_CAT_handshake_button_group_buttonClicked (int /* id */)
{
  set_rig_invariants ();
}

void Configuration::impl::on_rig_combo_box_currentIndexChanged (int /* index */)
{
  set_rig_invariants ();
  if(ui_->rig_combo_box->currentText().startsWith("OmniRig") || ui_->rig_combo_box->currentText().startsWith("DX Lab") ||
     ui_->rig_combo_box->currentText().startsWith("Ham Radio") || ui_->rig_combo_box->currentText().startsWith("Kenwood TS-480") ||
     ui_->rig_combo_box->currentText().startsWith("Kenwood TS-850") ||
     ui_->rig_combo_box->currentText().startsWith("Kenwood TS-870")) {
     ui_->PWR_and_SWR_check_box->setChecked (false);
     ui_->PWR_and_SWR_check_box->setEnabled (false);
     ui_->check_SWR_check_box->setChecked (false);
     ui_->check_SWR_check_box->setEnabled (false);
  }
}

void Configuration::impl::on_PWR_and_SWR_check_box_clicked(bool checked)
{
    if (checked) {
        ui_->check_SWR_check_box->setEnabled (true);
    } else {
        ui_->check_SWR_check_box->setEnabled (false);
    }
}

void Configuration::impl::on_cbHighDPI_clicked(bool checked)
{
  if (checked) {
      QFile::remove ("DisableHighDpiScaling");
  } else {
      static QFile f("DisableHighDpiScaling");
      f.open(QIODevice::WriteOnly | QIODevice::Text);
      QString EventConfig = ("DisableHighDpiScaling=\"true\"");
      QTextStream out(&f);
      out << EventConfig;
      f.close();
  }
}

void Configuration::impl::on_CAT_data_bits_button_group_buttonClicked (int /* id */)
{
  set_rig_invariants ();
}

void Configuration::impl::on_CAT_stop_bits_button_group_buttonClicked (int /* id */)
{
  set_rig_invariants ();
}

void Configuration::impl::on_CAT_poll_interval_spin_box_valueChanged (int /* value */)
{
  set_rig_invariants ();
}

void Configuration::impl::on_split_mode_button_group_buttonClicked (int /* id */)
{
  set_rig_invariants ();
}

void Configuration::impl::on_test_CAT_push_button_clicked ()
{
  if (!validate ())
    {
      return;
    }

  ui_->test_CAT_push_button->setStyleSheet ({});
  if (open_rig (true))
    {
       // Q_EMIT sync (true);
    }

  set_rig_invariants ();
}

void Configuration::impl::on_pbTestCloudlog_clicked ()
{
  //fprintf(stderr, "API URL: %s\n", ui_->leCloudlogApiUrl->text().toStdString().c_str());
  cloudlog_.testApi(ui_->leCloudlogApiUrl->text(), ui_->leCloudlogApiKey->text());
}

void Configuration::impl::on_gbCloudlog_clicked ()
{
  ui_->pbTestCloudlog->setStyleSheet ("QPushButton {background-color: none;}");
}

void Configuration::impl::on_test_PTT_push_button_clicked (bool checked)
{
  ui_->test_PTT_push_button->setChecked (!checked); // let status
                                                    // update check us
  if (!validate ())
    {
      return;
    }

  if (open_rig ())
    {
      Q_EMIT self_->transceiver_ptt (checked);
    }
}

void Configuration::impl::on_force_DTR_combo_box_currentIndexChanged (int /* index */)
{
  set_rig_invariants ();
}

void Configuration::impl::on_force_RTS_combo_box_currentIndexChanged (int /* index */)
{
  set_rig_invariants ();
}

void Configuration::impl::on_PTT_method_button_group_buttonClicked (int /* id */)
{
  set_rig_invariants ();
}

void Configuration::impl::on_refresh_push_button_clicked ()
{
  //
  // load combo boxes with audio setup choices
  //
//  default_audio_input_device_selected_ = load_audio_devices (QAudio::AudioInput, ui_->sound_input_combo_box, &audio_input_device_);
//  default_audio_output_device_selected_ = load_audio_devices (QAudio::AudioOutput, ui_->sound_output_combo_box, &audio_output_device_);

  update_audio_channels (ui_->sound_input_combo_box, ui_->sound_input_combo_box->currentIndex (), ui_->sound_input_channel_combo_box, false);
  update_audio_channels (ui_->sound_output_combo_box, ui_->sound_output_combo_box->currentIndex (), ui_->sound_output_channel_combo_box, true);

  ui_->sound_input_channel_combo_box->setCurrentIndex (audio_input_channel_);
  ui_->sound_output_channel_combo_box->setCurrentIndex (audio_output_channel_);

  restart_sound_input_device_ = false;
  restart_sound_output_device_ = false;
  restart_tci_device_ = false;
}

void Configuration::impl::on_tci_audio_check_box_clicked(bool checked)
{
  tci_audio_ = checked;
  if (is_tci_ && checked) {
    find_audio_devices ();
    ui_->sound_input_channel_combo_box->setCurrentIndex (0);
    ui_->sound_output_channel_combo_box->setCurrentIndex (0);
  }
}

void Configuration::impl::on_TCI_spin_box_valueChanged(double a)
{
  volume_ = a;
}


void Configuration::impl::on_add_macro_line_edit_editingFinished ()
{
  ui_->add_macro_line_edit->setText (ui_->add_macro_line_edit->text ().toUpper ());
}

void Configuration::impl::on_delete_macro_push_button_clicked (bool /* checked */)
{
  auto selection_model = ui_->macros_list_view->selectionModel ();
  if (selection_model->hasSelection ())
    {
      // delete all selected items
      delete_selected_macros (selection_model->selectedRows ());
    }
}

void Configuration::impl::delete_macro ()
{
  auto selection_model = ui_->macros_list_view->selectionModel ();
  if (!selection_model->hasSelection ())
    {
      // delete item under cursor if any
      auto index = selection_model->currentIndex ();
      if (index.isValid ())
        {
          next_macros_.removeRow (index.row ());
        }
    }
  else
    {
      // delete the whole selection
      delete_selected_macros (selection_model->selectedRows ());
    }
}

void Configuration::impl::delete_selected_macros (QModelIndexList selected_rows)
{
  // sort in reverse row order so that we can delete without changing
  // indices underneath us
  std::sort (selected_rows.begin (), selected_rows.end (), [] (QModelIndex const& lhs, QModelIndex const& rhs)
             {
               return rhs.row () < lhs.row (); // reverse row ordering
             });

  // now delete them
  Q_FOREACH (auto index, selected_rows)
    {
      next_macros_.removeRow (index.row ());
    }
}

void Configuration::impl::on_add_macro_push_button_clicked (bool /* checked */)
{
  if (next_macros_.insertRow (next_macros_.rowCount ()))
    {
      auto index = next_macros_.index (next_macros_.rowCount () - 1);
      ui_->macros_list_view->setCurrentIndex (index);
      next_macros_.setData (index, ui_->add_macro_line_edit->text ());
      ui_->add_macro_line_edit->clear ();
    }
}

void Configuration::impl::on_udp_server_line_edit_textChanged (QString const&)
{
  udp_server_name_edited_ = true;
}

void Configuration::impl::on_udp_server_line_edit_editingFinished ()
{
  if (this->isVisible())
  {
    int q1,q2,q3,q4;
    char tmpbuf[2];
    int n = sscanf(ui_->udp_server_line_edit->text ().trimmed ().toLatin1(), "%d.%d.%d.%d.%1s", &q1, &q2, &q3, &q4, tmpbuf);
    const char *iperr;
    switch(n)
    {
      case 0: iperr = "Error before first number";break;
      case 1: iperr = "Error between first and second number";break;
      case 2: iperr = "Error between second and third number";break;
      case 3: iperr = "Error between third and fourth number";break;
      case 4: iperr = ""; break;
      case 5: iperr = "Invalid characters after IP address"; break;
      default: iperr = "Unknown error parsing network address";
    }
    if (n != 4)
    {
       MessageBox::warning_message (this, tr ("Error in network address"), tr (iperr));
       return;
    }

  if (udp_server_name_edited_)
    {
      auto const& server = ui_->udp_server_line_edit->text ().trimmed ();
      QHostAddress ha {server};
      if (server.size () && ha.isNull ())
        {
          // queue a host address lookup
          // qDebug () << "server host DNS lookup:" << server;
#if QT_VERSION >= QT_VERSION_CHECK(5, 9, 0)
          dns_lookup_id_ = QHostInfo::lookupHost (server, this, &Configuration::impl::host_info_results);
#else
          dns_lookup_id_ = QHostInfo::lookupHost (server, this, SLOT (host_info_results (QHostInfo)));
#endif
        }
      else
        {
          check_multicast (ha);
        }
    }
  }
}

void Configuration::impl::host_info_results (QHostInfo host_info)
{
  if (host_info.lookupId () != dns_lookup_id_) return;
  dns_lookup_id_ = -1;
  if (QHostInfo::NoError != host_info.error ())
    {
      MessageBox::critical_message (this, tr ("UDP server DNS lookup failed"), host_info.errorString ());
    }
  else
    {
      auto const& server_addresses = host_info.addresses ();
      // qDebug () << "message server addresses:" << server_addresses;
      if (server_addresses.size ())
        {
          check_multicast (server_addresses[0]);
        }
    }
}

void Configuration::impl::check_multicast (QHostAddress const& ha)
{
  auto is_multicast = is_multicast_address (ha);
  ui_->udp_interfaces_label->setVisible (is_multicast);
  ui_->udp_interfaces_combo_box->setVisible (is_multicast);
  ui_->udp_TTL_label->setVisible (is_multicast);
  ui_->udp_TTL_spin_box->setVisible (is_multicast);
  if (isVisible ())
    {
      if (is_MAC_ambiguous_multicast_address (ha))
        {
          MessageBox::warning_message (this, tr ("MAC-ambiguous multicast groups addresses not supported"));
          find_tab (ui_->udp_server_line_edit);
          ui_->udp_server_line_edit->clear ();
        }
    }
  udp_server_name_edited_ = false;
}

void Configuration::impl::size_frequency_table_columns()
{
  ui_->frequencies_table_view->setVisible(false);
  ui_->frequencies_table_view->resizeColumnsToContents();
  ui_->frequencies_table_view->setVisible(true);
}

void Configuration::impl::delete_frequencies ()
{
  auto selection_model = ui_->frequencies_table_view->selectionModel ();
  selection_model->select (selection_model->selection (), QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows);
  next_frequencies_.removeDisjointRows (selection_model->selectedRows ());
  ui_->frequencies_table_view->resizeColumnToContents (FrequencyList_v2_101::mode_column);
  size_frequency_table_columns ();
}

void Configuration::impl::load_frequencies ()
{
  auto file_name = QFileDialog::getOpenFileName (this, tr ("Load Working Frequencies"), writeable_data_dir_.absolutePath (), tr ("Frequency files (*.qrg *.qrg.json);;All files (*.*)"));
  if (!file_name.isNull ())
    {
      auto const list = read_frequencies_file (file_name);
      if (list.size ()
          && (!next_frequencies_.frequency_list ().size ()
              || MessageBox::Yes == MessageBox::query_message (this
                                                               , tr ("Replace Working Frequencies")
                                                               , tr ("Are you sure you want to discard your current "
                                                                     "working frequencies and replace them with the "
                                                                     "loaded ones?"))))
        {
          next_frequencies_.frequency_list (list); // update the model
        }
      size_frequency_table_columns();
    }
}

void Configuration::impl::merge_frequencies ()
{
  auto file_name = QFileDialog::getOpenFileName (this, tr ("Merge Working Frequencies"), writeable_data_dir_.absolutePath (), tr ("Frequency files (*.qrg *.qrg.json);;All files (*.*)"));
  if (!file_name.isNull ())
    {
      next_frequencies_.frequency_list_merge (read_frequencies_file (file_name)); // update the model
      size_frequency_table_columns();
    }
}

FrequencyList_v2_101::FrequencyItems Configuration::impl::read_frequencies_file (QString const& file_name)
{
  QFile frequencies_file {file_name};
  frequencies_file.open (QFile::ReadOnly);
  QDataStream ids {&frequencies_file};
  FrequencyList_v2_101::FrequencyItems list;
  FrequencyList_v2::FrequencyItems list_v100;

  // read file as json if ends with qrg.json.
  if (file_name.endsWith(".qrg.json", Qt::CaseInsensitive))
    {
      try
        {
          list = FrequencyList_v2_101::from_json_file(&frequencies_file);
        }
      catch (ReadFileException const &e)
        {
          MessageBox::critical_message(this, tr("Error reading frequency file"), e.message_);
        }
      return list;
    }

  quint32 magic;
  ids >> magic;
  if (qrg_magic != magic)
    {
      MessageBox::warning_message (this, tr ("Not a valid frequencies file"), tr ("Incorrect file magic"));
      return list;
    }
  quint32 version;
  ids >> version;
  // handle version checks and QDataStream version here if
  // necessary
  if (version > qrg_version)
    {
      MessageBox::warning_message (this, tr ("Not a valid frequencies file"), tr ("Version is too new"));
      return list;
    }

  // de-serialize the data using version if necessary to
  // handle old schema
  if (version == qrg_version_100)
    {
      ids >> list_v100;
      Q_FOREACH (auto const& item, list_v100)
        {
          list << FrequencyList_v2_101::Item{item.frequency_, item.mode_, item.region_, QString(), QString(), QDateTime(),
                                         QDateTime(), false};
        }
    }
    else
    {
      ids >> list;
    }

  if (ids.status () != QDataStream::Ok || !ids.atEnd ())
    {
      MessageBox::warning_message (this, tr ("Not a valid frequencies file"), tr ("Contents corrupt"));
      list.clear ();
      return list;
    }
  return list;
}

void Configuration::impl::save_frequencies ()
{
  auto file_name = QFileDialog::getSaveFileName (this, tr ("Save Working Frequencies"), writeable_data_dir_.absolutePath (), tr ("Frequency files (*.qrg *.qrg.json);;All files (*.*)"));
  if (!file_name.isNull ())
    {
      bool b_write_json = file_name.endsWith(".qrg.json", Qt::CaseInsensitive);

      QFile frequencies_file {file_name};
      frequencies_file.open (QFile::WriteOnly);

      QDataStream ods {&frequencies_file};

      auto selection_model = ui_->frequencies_table_view->selectionModel ();
      if (selection_model->hasSelection ()
          && MessageBox::Yes == MessageBox::query_message (this
                                                           , tr ("Only Save Selected  Working Frequencies")
                                                           , tr ("Are you sure you want to save only the "
                                                                 "working frequencies that are currently selected? "
                                                                 "Click No to save all.")))
        {
          selection_model->select (selection_model->selection (), QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows);
          if (b_write_json)
            {
              next_frequencies_.to_json_file(&frequencies_file, "0x" + QString::number(qrg_magic, 16).toUpper(),
                                               "0x" + QString::number(qrg_version, 16).toUpper(),
                                               next_frequencies_.frequency_list(selection_model->selectedRows()));
            } else
            {
              ods << qrg_magic << qrg_version << next_frequencies_.frequency_list(selection_model->selectedRows());
            }
        }
      else
        {
          if (b_write_json)
            {
              next_frequencies_.to_json_file(&frequencies_file,
                                               "0x" + QString::number(qrg_magic, 16).toUpper(),
                                               "0x" + QString::number(qrg_version, 16).toUpper(),
                                                             next_frequencies_.frequency_list());
            } else
            {
              ods << qrg_magic << qrg_version << next_frequencies_.frequency_list();
            }
        }
    }
}

void Configuration::impl::reset_frequencies ()
{
  if (MessageBox::Yes == MessageBox::query_message (this, tr ("Reset Working Frequencies")
                                                    , tr ("Are you sure you want to discard your current "
                                                          "working frequencies and replace them with default "
                                                          "ones?")))
    {
      next_frequencies_.reset_to_defaults ();
    }
    size_frequency_table_columns ();
}

void Configuration::impl::insert_frequency ()
{
  if (QDialog::Accepted == frequency_dialog_->exec ())
    {
      ui_->frequencies_table_view->setCurrentIndex (next_frequencies_.add (frequency_dialog_->item ()));
      ui_->frequencies_table_view->resizeColumnToContents (FrequencyList_v2_101::mode_column);
      size_frequency_table_columns();
    }
}

void Configuration::impl::delete_stations ()
{
  auto selection_model = ui_->stations_table_view->selectionModel ();
  selection_model->select (selection_model->selection (), QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows);
  next_stations_.removeDisjointRows (selection_model->selectedRows ());
  ui_->stations_table_view->resizeColumnToContents (StationList::band_column);
  ui_->stations_table_view->resizeColumnToContents (StationList::offset_column);
}

void Configuration::impl::insert_station ()
{
  if (QDialog::Accepted == station_dialog_->exec ())
    {
      ui_->stations_table_view->setCurrentIndex (next_stations_.add (station_dialog_->station ()));
      ui_->stations_table_view->resizeColumnToContents (StationList::band_column);
      ui_->stations_table_view->resizeColumnToContents (StationList::offset_column);
    }
}

void Configuration::impl::on_save_path_select_push_button_clicked (bool /* checked */)
{
  QFileDialog fd {this, tr ("Save Directory"), ui_->save_path_display_label->text ()};
  fd.setFileMode (QFileDialog::Directory);
  fd.setOption (QFileDialog::ShowDirsOnly);
  if (fd.exec ())
    {
      if (fd.selectedFiles ().size ())
        {
          ui_->save_path_display_label->setText (fd.selectedFiles ().at (0));
        }
    }
}

void Configuration::impl::on_azel_path_select_push_button_clicked (bool /* checked */)
{
  QFileDialog fd {this, tr ("AzEl Directory"), ui_->azel_path_display_label->text ()};
  fd.setFileMode (QFileDialog::Directory);
  fd.setOption (QFileDialog::ShowDirsOnly);
  if (fd.exec ()) {
    if (fd.selectedFiles ().size ()) {
      ui_->azel_path_display_label->setText(fd.selectedFiles().at(0));
    }
  }
}

void Configuration::impl::on_calibration_intercept_spin_box_valueChanged (double)
{
  rig_active_ = false;          // force reset
}

void Configuration::impl::on_calibration_slope_ppm_spin_box_valueChanged (double)
{
  rig_active_ = false;          // force reset
}

void Configuration::impl::on_prompt_to_log_check_box_clicked(bool checked)
{
  if(checked) ui_->cbAutoLog->setChecked(false);
  ui_->cbContestingOnly->setEnabled(false);
}

void Configuration::impl::on_cbAutoLog_clicked(bool checked)
{
  ui_->cbContestingOnly->setEnabled(true);
  if(checked) ui_->prompt_to_log_check_box->setChecked(false);
}

void Configuration::impl::on_cbx2ToneSpacing_clicked(bool b)
{
  if(b) ui_->cbx4ToneSpacing->setChecked(false);
}

void Configuration::impl::on_cbx4ToneSpacing_clicked(bool b)
{
  if(b) ui_->cbx2ToneSpacing->setChecked(false);
}

void Configuration::impl::on_gbSpecialOpActivity_clicked (bool)
{
  check_visibility ();
}

void Configuration::impl::on_rbFox_clicked (bool)
{
  check_visibility ();
}

void Configuration::impl::on_rbHound_clicked (bool)
{
  check_visibility ();
}

void Configuration::impl::on_rbNA_VHF_Contest_clicked (bool)
{
  check_visibility ();
}

void Configuration::impl::on_rbEU_VHF_Contest_clicked (bool)
{
  check_visibility ();
}

void Configuration::impl::on_rbWW_DIGI_clicked (bool)
{
  check_visibility ();
}

void Configuration::impl::on_rbQ65pileup_clicked (bool)
{
  check_visibility ();
}

void Configuration::impl::on_rbField_Day_clicked (bool)
{
  check_visibility ();
}

void Configuration::impl::on_rbRTTY_Roundup_clicked (bool)
{
  check_visibility ();
}

void Configuration::impl::on_rbARRL_Digi_clicked (bool)
{
  check_visibility ();
}

void Configuration::impl::on_cbSuperFox_clicked (bool)
{
  check_visibility ();
}

void Configuration::impl::on_cbContestName_clicked (bool)
{
  check_visibility ();
}

void Configuration::impl::on_cb_NCCC_Sprint_clicked (bool)
{
  check_visibility ();
}

void Configuration::impl::on_cbOTP_clicked(bool)
{
  check_visibility();
}

void Configuration::impl::on_cbShowOTP_clicked(bool)
{
  check_visibility();
}

void Configuration::impl::check_visibility ()
{
  if (ui_->rbField_Day->isChecked() and ui_->gbSpecialOpActivity->isChecked()) {
    ui_->labFD->setEnabled (true);
    ui_->Field_Day_Exchange->setEnabled (true);
  } else {
    ui_->labFD->setEnabled (false);
    ui_->Field_Day_Exchange->setEnabled (false);
  }
  if (ui_->rbRTTY_Roundup->isChecked() and ui_->gbSpecialOpActivity->isChecked()) {
    ui_->labRTTY->setEnabled (true);
    ui_->RTTY_Exchange->setEnabled (true);
  } else {
    ui_->labRTTY->setEnabled (false);
    ui_->RTTY_Exchange->setEnabled (false);
  }
  if (ui_->cbContestName->isChecked() and !ui_->rbFox->isChecked() and !ui_->rbHound->isChecked()
      and  !ui_->rbQ65pileup->isChecked() and ui_->gbSpecialOpActivity->isChecked()) {
    ui_->labCN->setEnabled (true);
    ui_->Contest_Name->setEnabled (true);
  } else {
    ui_->labCN->setEnabled (false);
    ui_->Contest_Name->setEnabled (false);
  }
  if ((ui_->rbFox->isChecked() or ui_->rbHound->isChecked()) and ui_->gbSpecialOpActivity->isChecked()) {
    ui_->cbSuperFox->setEnabled (true);
    ui_->cbOTP->setEnabled (true);
  } else {
    ui_->cbSuperFox->setEnabled (false);
    ui_->cbOTP->setEnabled (false);
    ui_->cbShowOTP->setEnabled(false);
  }
  if (!ui_->rbFox->isChecked() and !ui_->rbHound->isChecked() and !ui_->rbQ65pileup->isChecked()
      and ui_->gbSpecialOpActivity->isChecked()) {
    ui_->cbContestName->setEnabled (true);
  } else {
    ui_->cbContestName->setEnabled (false);
  }
  if (ui_->rbNA_VHF_Contest->isChecked() and ui_->gbSpecialOpActivity->isChecked()) {
    ui_->cb_NCCC_Sprint->setEnabled (true);
  } else {
    ui_->cb_NCCC_Sprint->setEnabled (false);
  }
  if (!ui_->cbOTP->isChecked() or !ui_->gbSpecialOpActivity->isChecked()) {
    ui_->OTPSeed->setEnabled(false);
    ui_->OTPUrl->setEnabled(false);
    ui_->sbOTPinterval->setEnabled(false);
    ui_->lblOTPSeed->setEnabled(false);
    ui_->lblOTPUrl->setEnabled(false);
    ui_->lblOTPEvery->setEnabled(false);
    ui_->cbShowOTP->setEnabled(false);
  } else {
    if (ui_->rbHound->isChecked()) {
      if (ui_->OTPUrl->text().isEmpty())
      {
        ui_->OTPUrl->setText(FoxVerifier::default_url());
      }
      ui_->OTPUrl->setEnabled(true);
      ui_->lblOTPUrl->setEnabled(true);
      ui_->cbShowOTP->setEnabled(true);
    } else {
      ui_->OTPUrl->setEnabled(false);
      ui_->lblOTPUrl->setEnabled(false);
    }
    if (ui_->rbFox->isChecked()) {
      ui_->sbOTPinterval->setEnabled(true);
      ui_->OTPSeed->setEnabled(true);
      ui_->lblOTPSeed->setEnabled(true);
      ui_->lblOTPEvery->setEnabled(true);
      ui_->cbShowOTP->setEnabled(false);
    } else {
      ui_->OTPSeed->setEnabled(false);
      ui_->lblOTPSeed->setEnabled(false);
      ui_->lblOTPEvery->setEnabled(false);
      ui_->sbOTPinterval->setEnabled(false);
    }
  }
}
void Configuration::impl::on_OTPUrl_textEdited (QString const& url){
    auto text = url;
    if (text.size() == 0)
    {
      ui_->OTPUrl->setText(FoxVerifier::default_url());
    }
}
void Configuration::impl::on_OTPSeed_textEdited (QString const& url){
    ui_->OTPSeed->setText(url.toUpper());
}

void Configuration::impl::on_Field_Day_Exchange_editingFinished ()
{
  QString text = ui_->Field_Day_Exchange->text().toUpper();
  auto class_pos = text.indexOf (QRegularExpression {R"([A-H])"});
  if (class_pos >= 0 && text.size () >= class_pos + 2 && text.at (class_pos + 1) != QChar {' '})
    {
      text.insert (class_pos + 1, QChar {' '});
    }
  ui_->Field_Day_Exchange->setText (text);
}

void Configuration::impl::on_RTTY_Exchange_editingFinished ()
{
  ui_->RTTY_Exchange->setText (ui_->RTTY_Exchange->text ().toUpper ());
}

void Configuration::impl::on_Contest_Name_editingFinished ()
{
  ui_->Contest_Name->setText (ui_->Contest_Name->text ().toUpper ());
}

void Configuration::impl::on_cbSortAlphabetically_clicked (bool)
{
  sortAlphabetically_ = ui_->cbSortAlphabetically->isChecked();
}

void Configuration::impl::on_cbHideCARD_clicked (bool)
{
  hideCARD_ = ui_->cbHideCARD->isChecked();
}

void Configuration::impl::on_Blacklist1_editingFinished ()
{
  ui_->Blacklist1->setText (ui_->Blacklist1->text ().toUpper ());
}

void Configuration::impl::on_Blacklist2_editingFinished ()
{
  ui_->Blacklist2->setText (ui_->Blacklist2->text ().toUpper ());
}

void Configuration::impl::on_Blacklist3_editingFinished ()
{
  ui_->Blacklist3->setText (ui_->Blacklist3->text ().toUpper ());
}

void Configuration::impl::on_Blacklist4_editingFinished ()
{
  ui_->Blacklist4->setText (ui_->Blacklist4->text ().toUpper ());
}

void Configuration::impl::on_Blacklist5_editingFinished ()
{
  ui_->Blacklist5->setText (ui_->Blacklist5->text ().toUpper ());
}

void Configuration::impl::on_Blacklist6_editingFinished ()
{
  ui_->Blacklist6->setText (ui_->Blacklist6->text ().toUpper ());
}

void Configuration::impl::on_Blacklist7_editingFinished ()
{
  ui_->Blacklist7->setText (ui_->Blacklist7->text ().toUpper ());
}

void Configuration::impl::on_Blacklist8_editingFinished ()
{
  ui_->Blacklist8->setText (ui_->Blacklist8->text ().toUpper ());
}

void Configuration::impl::on_Blacklist9_editingFinished ()
{
  ui_->Blacklist9->setText (ui_->Blacklist9->text ().toUpper ());
}

void Configuration::impl::on_Blacklist10_editingFinished ()
{
  ui_->Blacklist10->setText (ui_->Blacklist10->text ().toUpper ());
}

void Configuration::impl::on_Blacklist11_editingFinished ()
{
  ui_->Blacklist11->setText (ui_->Blacklist11->text ().toUpper ());
}

void Configuration::impl::on_Blacklist12_editingFinished ()
{
  ui_->Blacklist12->setText (ui_->Blacklist12->text ().toUpper ());
}

void Configuration::impl::on_Whitelist1_editingFinished ()
{
  ui_->Whitelist1->setText (ui_->Whitelist1->text ().toUpper ());
}

void Configuration::impl::on_Whitelist2_editingFinished ()
{
  ui_->Whitelist2->setText (ui_->Whitelist2->text ().toUpper ());
}

void Configuration::impl::on_Whitelist3_editingFinished ()
{
  ui_->Whitelist3->setText (ui_->Whitelist3->text ().toUpper ());
}

void Configuration::impl::on_Whitelist4_editingFinished ()
{
  ui_->Whitelist4->setText (ui_->Whitelist4->text ().toUpper ());
}

void Configuration::impl::on_Whitelist5_editingFinished ()
{
  ui_->Whitelist5->setText (ui_->Whitelist5->text ().toUpper ());
}

void Configuration::impl::on_Whitelist6_editingFinished ()
{
  ui_->Whitelist6->setText (ui_->Whitelist6->text ().toUpper ());
}

void Configuration::impl::on_Whitelist7_editingFinished ()
{
  ui_->Whitelist7->setText (ui_->Whitelist7->text ().toUpper ());
}

void Configuration::impl::on_Whitelist8_editingFinished ()
{
  ui_->Whitelist8->setText (ui_->Whitelist8->text ().toUpper ());
}

void Configuration::impl::on_Whitelist9_editingFinished ()
{
  ui_->Whitelist9->setText (ui_->Whitelist9->text ().toUpper ());
}

void Configuration::impl::on_Whitelist10_editingFinished ()
{
  ui_->Whitelist10->setText (ui_->Whitelist10->text ().toUpper ());
}

void Configuration::impl::on_Whitelist11_editingFinished ()
{
  ui_->Whitelist11->setText (ui_->Whitelist11->text ().toUpper ());
}

void Configuration::impl::on_Whitelist12_editingFinished ()
{
  ui_->Whitelist12->setText (ui_->Whitelist12->text ().toUpper ());
}

void Configuration::impl::on_Pass1_editingFinished ()
{
  ui_->Pass1->setText (ui_->Pass1->text ().toUpper ());
}

void Configuration::impl::on_Pass2_editingFinished ()
{
  ui_->Pass2->setText (ui_->Pass2->text ().toUpper ());
}

void Configuration::impl::on_Pass3_editingFinished ()
{
  ui_->Pass3->setText (ui_->Pass3->text ().toUpper ());
}

void Configuration::impl::on_Pass4_editingFinished ()
{
  ui_->Pass4->setText (ui_->Pass4->text ().toUpper ());
}

void Configuration::impl::on_Pass5_editingFinished ()
{
  ui_->Pass5->setText (ui_->Pass5->text ().toUpper ());
}

void Configuration::impl::on_Pass6_editingFinished ()
{
  ui_->Pass6->setText (ui_->Pass6->text ().toUpper ());
}

void Configuration::impl::on_Pass7_editingFinished ()
{
  ui_->Pass7->setText (ui_->Pass7->text ().toUpper ());
}

void Configuration::impl::on_Pass8_editingFinished ()
{
  ui_->Pass8->setText (ui_->Pass8->text ().toUpper ());
}

void Configuration::impl::on_Pass9_editingFinished ()
{
  ui_->Pass9->setText (ui_->Pass9->text ().toUpper ());
}

void Configuration::impl::on_Pass10_editingFinished ()
{
  ui_->Pass10->setText (ui_->Pass10->text ().toUpper ());
}

void Configuration::impl::on_Pass11_editingFinished ()
{
  ui_->Pass11->setText (ui_->Pass11->text ().toUpper ());
}

void Configuration::impl::on_Pass12_editingFinished ()
{
  ui_->Pass12->setText (ui_->Pass12->text ().toUpper ());
}

void Configuration::impl::on_Territory1_editingFinished ()
{
  ui_->Territory1->setText (ui_->Territory1->text ());
}

void Configuration::impl::on_Territory2_editingFinished ()
{
  ui_->Territory2->setText (ui_->Territory2->text ());
}

void Configuration::impl::on_Territory3_editingFinished ()
{
  ui_->Territory3->setText (ui_->Territory3->text ());
}

void Configuration::impl::on_Territory4_editingFinished ()
{
  ui_->Territory4->setText (ui_->Territory4->text ());
}

void Configuration::impl::on_highlight_orange_callsigns_editingFinished ()
{
  ui_->highlight_orange_callsigns->setText (ui_->highlight_orange_callsigns->text ().toUpper ());
}

void Configuration::impl::on_highlight_blue_callsigns_editingFinished ()
{
  ui_->highlight_blue_callsigns->setText (ui_->highlight_blue_callsigns->text ().toUpper ());
}

bool Configuration::impl::have_rig ()
{
  if (!open_rig ())
    {
      MessageBox::critical_message (this, tr ("Rig control error")
                                    , tr ("Failed to open connection to rig"));
    }
  return rig_active_;
}

bool Configuration::impl::open_rig (bool force)
{
  auto result = false;

  auto const rig_data = gather_rig_data ();
  if (force || !rig_active_ || rig_data != saved_rig_params_)
    {
      try
        {
          if (is_tci_ && rig_active_ && tci_audio_) restart_tci_device_ = true;
          close_rig ();

          // create a new Transceiver object
          auto rig = transceiver_factory_.create (rig_data, transceiver_thread_);
          cached_rig_state_ = Transceiver::TransceiverState {};

          // hook up Configuration transceiver control signals to Transceiver slots
          //
          // these connections cross the thread boundary
          rig_connections_ << connect (this, &Configuration::impl::set_transceiver,
                                       rig.get (), &Transceiver::set);

          // hook up Transceiver signals to Configuration signals
          //
          // these connections cross the thread boundary
          rig_connections_ << connect (rig.get (), &Transceiver::resolution, this, [=] (int resolution) {
              rig_resolution_ = resolution;
            });
          rig_connections_ << connect (rig.get (), &Transceiver::tciframeswritten, this, &Configuration::impl::handle_transceiver_tciframeswritten);
          rig_connections_ << connect (rig.get (), &Transceiver::tci_mod_active, this, &Configuration::impl::handle_transceiver_tci_mod_active);
          rig_connections_ << connect (rig.get (), &Transceiver::update, this, &Configuration::impl::handle_transceiver_update);
          rig_connections_ << connect (rig.get (), &Transceiver::failure, this, &Configuration::impl::handle_transceiver_failure);

          // setup thread safe startup and close down semantics
          rig_connections_ << connect (this, &Configuration::impl::start_transceiver, rig.get (), &Transceiver::start);
          rig_connections_ << connect (this, &Configuration::impl::stop_transceiver, rig.get (), &Transceiver::stop);

          auto p = rig.release ();	// take ownership

          // schedule destruction on thread quit
          connect (transceiver_thread_, &QThread::finished, p, &QObject::deleteLater);

          // schedule eventual destruction for non-closing situations
          //
          // must   be   queued    connection   to   avoid   premature
          // self-immolation  since finished  signal  is  going to  be
          // emitted from  the object that  will get destroyed  in its
          // own  stop  slot  i.e.  a   same  thread  signal  to  slot
          // connection which by  default will be reduced  to a method
          // function call.
          connect (p, &Transceiver::finished, p, &Transceiver::deleteLater, Qt::QueuedConnection);

          ui_->test_CAT_push_button->setStyleSheet ({});
          rig_active_ = true;
          LOG_TRACE ("emitting startup_transceiver");
          Q_EMIT start_transceiver (++transceiver_command_number_); // start rig on its thread
          if(is_tci_) rig_params_ = gather_rig_data ();
          result = true;
        }
      catch (std::exception const& e)
        {
          qDebug() << "Configuration::impl::open_rig failed with error " << e.what();
          handle_transceiver_failure (e.what ());
        }

      saved_rig_params_ = rig_data;
      rig_changed_ = true;
    }
  else
    {
      result = true;
    }
  return result;
}

void Configuration::impl::set_cached_mode ()
{
  MODE mode {Transceiver::UNK};
  // override cache mode with what we want to enforce which includes
  // UNK (unknown) where we want to leave the rig mode untouched
  switch (data_mode_)
    {
    case data_mode_USB: mode = Transceiver::USB; break;
    case data_mode_data: mode = Transceiver::DIG_U; break;
    default: break;
    }

  cached_rig_state_.mode (mode);
}

void Configuration::impl::transceiver_frequency (Frequency f)
{
  cached_rig_state_.online (true); // we want the rig online
  set_cached_mode ();

  // apply any offset & calibration
  // we store the offset here for use in feedback from the rig, we
  // cannot absolutely determine if the offset should apply but by
  // simply picking an offset when the Rx frequency is set and
  // sticking to it we get sane behaviour
  current_offset_ = stations_.offset (f);
  cached_rig_state_.frequency (apply_calibration (f + current_offset_));

  // qDebug () << "Configuration::impl::transceiver_frequency: n:" << transceiver_command_number_ + 1 << "f:" << f;
  LOG_TRACE ("emitting set_transceiver: requested state:" << cached_rig_state_);
  Q_EMIT set_transceiver (cached_rig_state_, ++transceiver_command_number_);
}

void Configuration::impl::transceiver_tx_frequency (Frequency f)
{
  Q_ASSERT (!f || split_mode ());
  if (split_mode ())
    {
      cached_rig_state_.online (true); // we want the rig online
      set_cached_mode ();
      cached_rig_state_.split (f);
      cached_rig_state_.tx_frequency (f);

      // lookup offset for tx and apply calibration
      if (f)
        {
          // apply and offset and calibration
          // we store the offset here for use in feedback from the
          // rig, we cannot absolutely determine if the offset should
          // apply but by simply picking an offset when the Rx
          // frequency is set and sticking to it we get sane behaviour
          current_tx_offset_ = stations_.offset (f);
          cached_rig_state_.tx_frequency (apply_calibration (f + current_tx_offset_));
        }

      // qDebug () << "Configuration::impl::transceiver_tx_frequency: n:" << transceiver_command_number_ + 1 << "f:" << f;
      LOG_TRACE ("emitting set_transceiver: requested state:" << cached_rig_state_);
      Q_EMIT set_transceiver (cached_rig_state_, ++transceiver_command_number_);
    }
}

void Configuration::impl::transceiver_mode (MODE m)
{
  cached_rig_state_.online (true); // we want the rig online
  cached_rig_state_.mode (m);
  // qDebug () << "Configuration::impl::transceiver_mode: n:" << transceiver_command_number_ + 1 << "m:" << m;
  LOG_TRACE ("emitting set_transceiver: requested state:" << cached_rig_state_);
  Q_EMIT set_transceiver (cached_rig_state_, ++transceiver_command_number_);
}

void Configuration::impl::transceiver_ptt (bool on)
{
  cached_rig_state_.online (true); // we want the rig online
  set_cached_mode ();
  cached_rig_state_.ptt (on);
  // qDebug () << "Configuration::impl::transceiver_ptt: n:" << transceiver_command_number_ + 1 << "on:" << on;
  LOG_TRACE ("emitting set_transceiver: requested state:" << cached_rig_state_);
  Q_EMIT set_transceiver (cached_rig_state_, ++transceiver_command_number_);
}

void Configuration::impl::transceiver_audio (bool on)
{
  cached_rig_state_.online (true); // we want the rig online
  set_cached_mode ();
  if (cached_rig_state_.audio() != on)
  {
    cached_rig_state_.audio (on);
//    printf("%s(%0.1f) Configuration #:%d audio: %d\n",QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),transceiver_command_number_+1,on);
    Q_EMIT set_transceiver (cached_rig_state_, ++transceiver_command_number_);
  }
}

void Configuration::impl::transceiver_tune (bool on)
{
  cached_rig_state_.online (true); // we want the rig online
  set_cached_mode ();
  //cached_rig_state_.ptt (on);
  cached_rig_state_.tune (on);
  // qDebug () << "Configuration::impl::transceiver_ptt: n:" << transceiver_command_number_ + 1 << "on:" << on;
  LOG_TRACE ("emitting set_transceiver: requested state:" << cached_rig_state_);
  Q_EMIT set_transceiver (cached_rig_state_, ++transceiver_command_number_);
}


void Configuration::impl::transceiver_period (double period)
{
  cached_rig_state_.online (true); // we want the rig online
  set_cached_mode ();
  if (cached_rig_state_.period() != period)
  {
//    printf("%s(%0.1f) Configuration #:%d period: %0.1f cached: %0.1f\n",QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),transceiver_command_number_+1,period,cached_rig_state_.period());
    cached_rig_state_.period (period);
    Q_EMIT set_transceiver (cached_rig_state_, ++transceiver_command_number_);
  }
}

void Configuration::impl::transceiver_blocksize (qint32 blocksize)
{
  cached_rig_state_.online (true); // we want the rig online
  set_cached_mode ();
  if (cached_rig_state_.blocksize() != blocksize)
  {
//    printf("%s(%0.1f) Configuration #:%d blocksize: %d cached:%d\n",QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),transceiver_command_number_+1,blocksize,cached_rig_state_.blocksize());
    cached_rig_state_.blocksize (blocksize);
    Q_EMIT set_transceiver (cached_rig_state_, ++transceiver_command_number_);
  }
}

void Configuration::impl::transceiver_spread (double spread)
{
  cached_rig_state_.online (true); // we want the rig online
  set_cached_mode ();
  if (cached_rig_state_.spread() != spread)
  {
//    printf("%s(%0.1f) Configuration #:%d spread: %0.1f cached: %0.1f\n",QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),transceiver_command_number_+1,spread,cached_rig_state_.spread());
    cached_rig_state_.spread (spread);
    Q_EMIT set_transceiver (cached_rig_state_, ++transceiver_command_number_);
  }
}

void Configuration::impl::transceiver_nsym (int nsym)
{
  cached_rig_state_.online (true); // we want the rig online
  set_cached_mode ();
  if (cached_rig_state_.nsym() != nsym)
  {
//    printf("%s(%0.1f) Configuration #:%d nsym: %d cached:%d\n",QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),transceiver_command_number_+1,nsym,cached_rig_state_.nsym());
    cached_rig_state_.nsym (nsym);
    Q_EMIT set_transceiver (cached_rig_state_, ++transceiver_command_number_);
  }
}

void Configuration::impl::transceiver_trfrequency (double trfrequency)
{
  cached_rig_state_.online (true); // we want the rig online
  set_cached_mode ();
  if (cached_rig_state_.trfrequency() != trfrequency)
  {
//    printf("%s(%0.1f) Configuration #:%d trfrequency: %0.1f cached: %0.1f\n",QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),transceiver_command_number_+1,trfrequency,cached_rig_state_.trfrequency());
    cached_rig_state_.trfrequency (trfrequency);
    Q_EMIT set_transceiver (cached_rig_state_, ++transceiver_command_number_);
  }
}

void Configuration::impl::transceiver_txvolume (double txvolume)
{
  cached_rig_state_.online (true); // we want the rig online
  set_cached_mode ();
  if (cached_rig_state_.txvolume() != txvolume)
  {
//    printf("%s(%0.1f) Configuration #:%d txvolume: %0.1f cached: %0.1f\n",QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),transceiver_command_number_+1,txvolume,cached_rig_state_.txvolume());
    cached_rig_state_.txvolume (txvolume);
    Q_EMIT set_transceiver (cached_rig_state_, ++transceiver_command_number_);
  }
}

void Configuration::impl::transceiver_volume (double volume)
{
  cached_rig_state_.online (true); // we want the rig online
  set_cached_mode ();
  if (cached_rig_state_.volume() != volume)
  {
    //printf("In Configuration::transceiver_volume, volume: %f cached: %f\n",volume,cached_rig_state_.volume());
    cached_rig_state_.volume (volume);
    Q_EMIT set_transceiver (cached_rig_state_, ++transceiver_command_number_);
  }
}

void Configuration::impl::transceiver_modulator_start (QString jtmode, unsigned symbolslength, double framespersymbol, double frequency, double tonespacing, bool synchronize, bool fastmode, double dbsnr, double trperiod)
{
  cached_rig_state_.online (true); // we want the rig online
  set_cached_mode ();
  if (!cached_rig_state_.tx_audio())
  {
    cached_rig_state_.tx_audio (true);
    cached_rig_state_.symbolslength (symbolslength);
    cached_rig_state_.framespersymbol (framespersymbol);
    cached_rig_state_.trfrequency (frequency);
    cached_rig_state_.tonespacing (tonespacing);
    cached_rig_state_.synchronize (synchronize);
    cached_rig_state_.dbsnr (dbsnr);
    cached_rig_state_.trperiod (trperiod);
    cached_rig_state_.jtmode(jtmode);
    cached_rig_state_.fastmode(fastmode);
    //    printf("%s(%0.1f) Configuration #:%d modulator_start: symbolslength=%d framespersymbol=%0.1f frequency=%0.1f tonespacing=%0.1f synchronize= %d dbsnr=%0.1f trperiod=%0.1f\n",QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),transceiver_command_number_+1,symbolslength,framespersymbol,frequency,tonespacing,synchronize,dbsnr,trperiod);
    Q_EMIT set_transceiver (cached_rig_state_, ++transceiver_command_number_);
  }
//  else printf("%s(%0.1f) Configuration modulator_start: WAS ALLREADY RUNNING\n",QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str());
}

void Configuration::impl::transceiver_modulator_stop (bool on)
{
  cached_rig_state_.online (true); // we want the rig online
  set_cached_mode ();
  if (cached_rig_state_.tx_audio())
  {
    cached_rig_state_.tx_audio (false);
    cached_rig_state_.quick (on);
//    printf("%s(%0.1f) Configuration #:%d modulator_stop: quick=%d\n",QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str(),transceiver_command_number_+1,on);
    Q_EMIT set_transceiver (cached_rig_state_, ++transceiver_command_number_);
  }
//  else printf("%s(%0.1f) Configuration modulator_stop: WAS NOT RUNNING\n",QDateTime::currentDateTimeUtc().toString("hh:mm:ss.zzz").toStdString().c_str());
}

void Configuration::impl::sync_transceiver (bool /*force_signal*/)
{
  // pass this on as cache must be ignored
  // Q_EMIT sync (force_signal);
}

void Configuration::impl::handle_transceiver_tciframeswritten (qint64 count)
{
  Q_EMIT self_->transceiver_TCIframesWritten (count);
}

void Configuration::impl::handle_transceiver_tci_mod_active (bool on)
{
  Q_EMIT self_->transceiver_TCImodActive (on);
}

void Configuration::impl::handle_leavingSettings ()
{
  Q_EMIT self_->leavingSettings (true);
}

void Configuration::impl::handle_transceiver_update (TransceiverState const& state,
                                                     unsigned sequence_number)
{
  LOG_TRACE ("#: " << sequence_number << ' ' << state);

  // only follow rig on some information, ignore other stuff
  cached_rig_state_.online (state.online ());
  cached_rig_state_.frequency (state.frequency ());
  if(!is_tci_) cached_rig_state_.mode (state.mode ());  //was not present in jtdx
  cached_rig_state_.split (state.split ());

  if (state.online ())
    {
      ui_->test_PTT_push_button->setChecked (state.ptt ());

      if (isVisible ())
        {
          ui_->test_CAT_push_button->setStyleSheet ("QPushButton {background-color: green;}");

          auto const& rig = ui_->rig_combo_box->currentText ();
          auto ptt_method = static_cast<TransceiverFactory::PTTMethod> (ui_->PTT_method_button_group->checkedId ());
          auto CAT_PTT_enabled = transceiver_factory_.has_CAT_PTT (rig);
          ui_->test_PTT_push_button->setEnabled ((TransceiverFactory::PTT_method_CAT == ptt_method && CAT_PTT_enabled)
                                                 || TransceiverFactory::PTT_method_DTR == ptt_method
                                                 || TransceiverFactory::PTT_method_RTS == ptt_method);
        }
    }
  else
    {
      if (is_tci_) {
      	if (sequence_number == transceiver_command_number_)  close_rig (); 
      }
      else close_rig();
    }

  // pass on to clients if current command is processed
  if (sequence_number == transceiver_command_number_)
    {
      TransceiverState reported_state {state};
      // take off calibration & offset
      reported_state.frequency (remove_calibration (reported_state.frequency ()) - current_offset_);

      if (reported_state.tx_frequency ())
        {
          // take off calibration & offset
          reported_state.tx_frequency (remove_calibration (reported_state.tx_frequency ()) - current_tx_offset_);
        }

      Q_EMIT self_->transceiver_update (reported_state);
    }
}

void Configuration::impl::handle_transceiver_failure (QString const& reason)
{
  LOG_ERROR ("handle_transceiver_failure: reason: " << reason);
  qDebug() << "Configuration::impl::handle_transceiver_failure called with reason: " << reason << "\n";
  close_rig ();
  ui_->test_PTT_push_button->setChecked (false);

  if (isVisible ())
    {
      MessageBox::critical_message (this, tr ("Rig failure"), reason);
    }
  else
    {
      // pass on if our dialog isn't active
      Q_EMIT self_->transceiver_failure (reason);
    }
}

void Configuration::impl::close_rig ()
{
  ui_->test_PTT_push_button->setEnabled (false);

  // revert to no rig configured
  if (rig_active_)
    {
      ui_->test_CAT_push_button->setStyleSheet ("QPushButton {background-color: red;}");
      LOG_TRACE ("emitting stop_transceiver");
      Q_EMIT stop_transceiver ();
      if (is_tci_) QThread::msleep (100);
      for (auto const& connection: rig_connections_)
        {
          disconnect (connection);
        }
      rig_connections_.clear ();
      rig_active_ = false;
    }
}

// find the audio device that matches the specified name, also
// populate into the selection combo box with any devices we find in
// the search
QAudioDeviceInfo Configuration::impl::find_audio_device (QAudio::Mode mode, QComboBox * combo_box
                                                         , QString const& device_name)
{
  using std::copy;
  using std::back_inserter;

  if (device_name.size ())
    {
      Q_EMIT self_->enumerating_audio_devices ();
      auto const& devices = QAudioDeviceInfo::availableDevices (mode);
      Q_FOREACH (auto const& p, devices)
        {
          // qDebug () << "Configuration::impl::find_audio_device: input:" << (QAudio::AudioInput == mode) << "name:" << p.deviceName () << "preferred format:" << p.preferredFormat () << "endians:" << p.supportedByteOrders () << "codecs:" << p.supportedCodecs () << "channels:" << p.supportedChannelCounts () << "rates:" << p.supportedSampleRates () << "sizes:" << p.supportedSampleSizes () << "types:" << p.supportedSampleTypes ();
          if (p.deviceName () == device_name)
            {
              // convert supported channel counts into something we can store in the item model
              QList<QVariant> channel_counts;
              auto scc = p.supportedChannelCounts ();
              copy (scc.cbegin (), scc.cend (), back_inserter (channel_counts));
              combo_box->insertItem (0, device_name, QVariant::fromValue (audio_info_type {p, channel_counts}));
              combo_box->setCurrentIndex (0);
              return p;
            }
        }
      // insert a place holder for the not found device
      if(!tci_audio_) combo_box->insertItem (0, device_name + " (" + tr ("Not found", "audio device missing") + ")", QVariant::fromValue (audio_info_type {}));
      else {
          combo_box->insertItem (0, "TCI audio", QVariant::fromValue (audio_info_type {}));
      }
      combo_box->setCurrentIndex (0);
    }
  return {};
}

// load the available audio devices into the selection combo box
void Configuration::impl::load_audio_devices(QAudio::Mode mode, QComboBox * combo_box, QAudioDeviceInfo * device)
{
    using std::copy;
    using std::back_inserter;

    QString selected_device_name = combo_box->currentText(); // Get the currently selected item text
    combo_box->clear();

    Q_EMIT self_->enumerating_audio_devices();
    auto const& devices = QAudioDeviceInfo::availableDevices(mode);

    printf ("rig_active_ is: %d and tci_audio_ is %d\n", rig_active_, tci_audio_);
    qDebug () << "qDebug says rig_active_ is: " << rig_active_ << '\n';
    qDebug () << "qDebug says tci_audio_ is: " << tci_audio_ << '\n';
    int current_index = -1;
    if (is_tci_ && tci_audio_) {
          QList<QVariant> channel_counts;
          QList<int> scc({1});
          copy (scc.cbegin (), scc.cend (), back_inserter (channel_counts));
          combo_box->addItem ("TCI audio", channel_counts);
          current_index = 0;
          return;
    }

    // Use a vector to store device names and associated audio_info_type
    std::vector<std::pair<QString, audio_info_type>> device_items;

    Q_FOREACH(auto const& p, devices)
    {
        // Check if the device supports the "audio/pcm" codec
        if (!p.supportedCodecs().contains("audio/pcm")) {
            continue; // Skip devices that do not support "audio/pcm"
        }
#ifndef WIN32
        if (hideCARD_ && p.deviceName().contains("CARD=")) {
            continue; // skip ALSA devices on Linux -- we never use them
        }
#endif
        // Convert supported channel counts into something we can store in the item model
        QList<QVariant> channel_counts;
        auto scc = p.supportedChannelCounts();
        copy(scc.cbegin(), scc.cend(), back_inserter(channel_counts));

        audio_info_type info = qMakePair(p, channel_counts);
        device_items.emplace_back(p.deviceName(), info);
    }

    // Sort the device items by device name
    if (sortAlphabetically_) {
      std::sort(device_items.begin(), device_items.end(), [](const std::pair<QString, audio_info_type>& a, const std::pair<QString, audio_info_type>& b) {
          return a.first.toLower() < b.first.toLower();
      });
    }

    // Add the sorted items back to the combo box
    for (int i = 0; i < static_cast<int>(device_items.size()); ++i)
    {
        const auto& item = device_items[i];
        combo_box->addItem(item.first, QVariant::fromValue(item.second));

        // Match the device name with the currently selected combo box item
        if (device->deviceName() == item.first)
        {
            current_index = i;
            combo_box->setCurrentIndex(current_index);
        }
    }
}


// load the available network interfaces into the selection combo box
void Configuration::impl::load_network_interfaces (CheckableItemComboBox * combo_box, QStringList current)
{
  combo_box->clear ();
  for (auto const& net_if : QNetworkInterface::allInterfaces ())
    {
      auto flags = QNetworkInterface::IsUp | QNetworkInterface::CanMulticast;
      if ((net_if.flags () & flags) == flags)
        {
          bool check_it = current.contains (net_if.name ());
          if (net_if.flags () & QNetworkInterface::IsLoopBack)
            {
              loopback_interface_name_ = net_if.name ();
              if (!current.size ())
                {
                  check_it = true;
                }
            }
          auto item = combo_box->addCheckItem (net_if.humanReadableName ()
                                               , net_if.name ()
                                               , check_it ? Qt::Checked : Qt::Unchecked);
          auto tip = QString {"name(index): %1(%2) - %3"}.arg (net_if.name ()).arg (net_if.index ())
                       .arg (net_if.flags () & QNetworkInterface::IsUp ? "Up" : "Down");
          auto hw_addr = net_if.hardwareAddress ();
          if (hw_addr.size ())
            {
              tip += QString {"\nhw: %1"}.arg (net_if.hardwareAddress ());
            }
          auto aes = net_if.addressEntries ();
          if (aes.size ())
            {
              tip += "\naddresses:";
              for (auto const& ae : aes)
                {
                  tip += QString {"\n  ip: %1/%2"}.arg (ae.ip ().toString ()).arg (ae.prefixLength ());
                }
            }
          item->setToolTip (tip);
        }
    }
}

// get the select network interfaces from the selection combo box
void Configuration::impl::validate_network_interfaces (QString const& /*text*/)
{
  auto model = static_cast<QStandardItemModel *> (ui_->udp_interfaces_combo_box->model ());
  bool has_checked {false};
  int loopback_row {-1};
  for (int row = 0; row < model->rowCount (); ++row)
    {
      if (model->item (row)->data ().toString () == loopback_interface_name_)
        {
          loopback_row = row;
        }
      else if (Qt::Checked == model->item (row)->checkState ())
        {
          has_checked = true;
        }
    }
  if (loopback_row >= 0)
    {
      if (!has_checked)
        {
          model->item (loopback_row)->setCheckState (Qt::Checked);
        }
      model->item (loopback_row)->setEnabled (has_checked);
    }
}

// get the select network interfaces from the selection combo box
QStringList Configuration::impl::get_selected_network_interfaces (CheckableItemComboBox * combo_box)
{
  QStringList interfaces;
  auto model = static_cast<QStandardItemModel *> (combo_box->model ());
  for (int row = 0; row < model->rowCount (); ++row)
    {
      if (Qt::Checked == model->item (row)->checkState ())
        {
          interfaces << model->item (row)->data ().toString ();
        }
    }
  return interfaces;
}

// enable only the channels that are supported by the selected audio device
void Configuration::impl::update_audio_channels (QComboBox const * source_combo_box, int index, QComboBox * combo_box, bool allow_both)
{
  // disable all items
  for (int i (0); i < combo_box->count (); ++i)
    {
      combo_box->setItemData (i, combo_box_item_disabled, Qt::UserRole - 1);
    }

  Q_FOREACH (QVariant const& v
             , (source_combo_box->itemData (index).value<audio_info_type> ().second))
    {
      // enable valid options
      int n {v.toInt ()};
      if (2 == n)
        {
          combo_box->setItemData (AudioDevice::Left, combo_box_item_enabled, Qt::UserRole - 1);
          combo_box->setItemData (AudioDevice::Right, combo_box_item_enabled, Qt::UserRole - 1);
          if (allow_both)
            {
              combo_box->setItemData (AudioDevice::Both, combo_box_item_enabled, Qt::UserRole - 1);
            }
        }
      else if (1 == n)
        {
          combo_box->setItemData (AudioDevice::Mono, combo_box_item_enabled, Qt::UserRole - 1);
        }
    }
}

void Configuration::impl::find_tab (QWidget * target)
{
  for (auto * parent = target->parentWidget (); parent; parent = parent->parentWidget ())
    {
      auto index = ui_->configuration_tabs->indexOf (parent);
      if (index != -1)
        {
          ui_->configuration_tabs->setCurrentIndex (index);
          break;
        }
    }
  target->setFocus ();
}

// load all the supported rig names into the selection combo box
void Configuration::impl::enumerate_rigs ()
{
  ui_->rig_combo_box->clear ();

  auto rigs = transceiver_factory_.supported_transceivers ();

  for (auto r = rigs.cbegin (); r != rigs.cend (); ++r)
    {
      if ("None" == r.key ())
        {
          // put None first
          ui_->rig_combo_box->insertItem (0, r.key (), r.value ().model_number_);
        }
      else
        {
          int i;
          for(i=1;i<ui_->rig_combo_box->count() && (r.key().toLower() > ui_->rig_combo_box->itemText(i).toLower());++i);
          if (i < ui_->rig_combo_box->count())  ui_->rig_combo_box->insertItem (i, r.key (), r.value ().model_number_);
          else ui_->rig_combo_box->addItem (r.key (), r.value ().model_number_);
        }
    }

  ui_->rig_combo_box->setCurrentText (rig_params_.rig_name);
}

void Configuration::impl::fill_port_combo_box(QComboBox* cb)
{
    auto current_text = cb->currentText();
    cb->clear();

    // Retrieve available ports and filter out ones with "NULL"
    QList<QSerialPortInfo> ports;
    foreach (const QSerialPortInfo &p, QSerialPortInfo::availablePorts())
    {
        if (!p.portName().contains("NULL")) // virtual serial port pairs
        {
            ports.append(p);
        }
    }

    // Sort ports by the numeric value of the port name, if possible
    std::sort(ports.begin(), ports.end(), [](const QSerialPortInfo& a, const QSerialPortInfo& b) {
        bool isANumeric = a.portName().midRef(3).toInt();
        bool isBNumeric = b.portName().midRef(3).toInt();
        if (isANumeric && isBNumeric)
        {
            return a.portName().midRef(3).toInt() < b.portName().midRef(3).toInt();
        }
        else if (isANumeric)
        {
            return true; // a comes before b
        }
        else if (isBNumeric)
        {
            return false; // b comes before a
        }
        else
        {
            return a.portName() < b.portName(); // Alphabetical order for non-numeric ports
        }
    });

    // Add sorted ports to the combo box
    for (const auto& p : ports)
    {
        // Remove possibly confusing Windows device path (OK because it gets added back by Hamlib)
        cb->addItem(p.systemLocation().remove(QRegularExpression{R"(^\\\\\.\\)"}));

        auto tip = QString{"%1 %2 %3"}.arg(p.manufacturer()).arg(p.serialNumber()).arg(p.description()).trimmed();
        if (tip.size())
        {
            cb->setItemData(cb->count() - 1, tip, Qt::ToolTipRole);
        }
    }

    cb->addItem("USB");
    cb->setItemData(cb->count() - 1, "Custom USB device", Qt::ToolTipRole);
    cb->setEditText(current_text);
}

auto Configuration::impl::apply_calibration (Frequency f) const -> Frequency
{
  if (frequency_calibration_disabled_) return f;
  return std::llround (calibration_.intercept
                       + (1. + calibration_.slope_ppm / 1.e6) * f);
}

auto Configuration::impl::remove_calibration (Frequency f) const -> Frequency
{
  if (frequency_calibration_disabled_) return f;
  return std::llround ((f - calibration_.intercept)
                       / (1. + calibration_.slope_ppm / 1.e6));
}

ENUM_QDATASTREAM_OPS_IMPL (Configuration, DataMode);
ENUM_QDATASTREAM_OPS_IMPL (Configuration, Type2MsgGen);

ENUM_CONVERSION_OPS_IMPL (Configuration, DataMode);
ENUM_CONVERSION_OPS_IMPL (Configuration, Type2MsgGen);