File: tqsl.cpp

package info (click to toggle)
trustedqsl 2.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 19,964 kB
  • ctags: 3,229
  • sloc: cpp: 20,654; xml: 4,289; ansic: 624; sh: 57; python: 18; makefile: 11
file content (5439 lines) | stat: -rw-r--r-- 187,213 bytes parent folder | download
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
/***************************************************************************
                                  tqsl.cpp
                             -------------------
    begin                : Mon Nov 4 2002
    copyright            : (C) 2002-2014 by ARRL and the TrustedQSL Developers
    author               : Jon Bloom
    email                : jbloom@arrl.org
 ***************************************************************************/

#include <curl/curl.h> // has to be before something else in this list
#include <stdlib.h>
#include <errno.h>
#ifndef _WIN32
#include <unistd.h>
#include <fcntl.h>
#endif
#include <expat.h>
#include <sys/stat.h>

#include <wx/wxprec.h>
#include <wx/object.h>
#include <wx/wxchar.h>
#include <wx/config.h>
#include <wx/regex.h>
#include <wx/tokenzr.h>
#include <wx/hashmap.h>
#include <wx/hyperlink.h>
#include <wx/cmdline.h>
#include <wx/notebook.h>
#include <wx/statline.h>
#include <wx/app.h>
#include <wx/stdpaths.h>

#ifdef __BORLANDC__
	#pragma hdrstop
#endif

#ifndef WX_PRECOMP
	#include <wx/wx.h>
#endif

#include <wx/wxhtml.h>
#include <wx/wfstream.h>

#ifdef _MSC_VER //could probably do a more generic check here...
// stdint exists on vs2012 and (I think) 2010, but not 2008 or its platform
  #define uint8_t unsigned char
#else
#include <stdint.h> //for uint8_t; should be cstdint but this is C++11 and not universally supported
#endif

#ifdef _WIN32
	#include <io.h>
#endif
#include <zlib.h>
#include <openssl/opensslv.h> // only for version info!
#include <db.h> //only for version info!

#include <iostream>
#include <fstream>
#include <memory>
#include <string>
#include <vector>
#include <map>

#ifdef HAVE_CONFIG_H
#include "sysconfig.h"
#endif

#include "tqslhelp.h"
#include "tqsltrace.h"

#include "crqwiz.h"
#include "getpassword.h"
#include "loadcertwiz.h"
#include "tqsllib.h"
#include "util.h"
#include "wxutil.h"

#include "tqslwiz.h"
#include "qsodatadialog.h"
#include "tqslerrno.h"
#include "tqslexcept.h"
#include "tqslpaths.h"
#include "stationdial.h"
#include "tqslconvert.h"
#include "dxcc.h"
#include "tqsl_prefs.h"
#include "tqslbuild.h"
#include "tqslapp.h"

#include "winstrdefs.h"

using std::ifstream;
using std::ios;
using std::ofstream;
using std::cerr;
using std::endl;
using std::vector;
using std::string;

#ifdef _WIN32
#include "key.xpm"
#else
#include "key-new.xpm"
#endif
#include "save.xpm"
#include "upload.xpm"
#include "upload_dis.xpm"
#include "file_edit.xpm"
#include "file_edit_dis.xpm"
#include "loc_add.xpm"
#include "loc_add_dis.xpm"
#include "delete.xpm"
#include "delete_dis.xpm"
#include "edit.xpm"
#include "edit_dis.xpm"
#include "download.xpm"
#include "download_dis.xpm"
#include "properties.xpm"
#include "properties_dis.xpm"
#include "import.xpm"
#include "lotw.xpm"

/// GEOMETRY

#define LABEL_HEIGHT 20
#define LABEL_WIDTH 120

#define CERTLIST_FLAGS TQSL_SELECT_CERT_WITHKEYS | TQSL_SELECT_CERT_SUPERCEDED | TQSL_SELECT_CERT_EXPIRED

static wxMenu *stn_menu;

static wxString flattenCallSign(const wxString& call);

static wxString ErrorTitle(wxT("TQSL Error"));

static bool verify_cert(tQSL_Location loc, bool editing);

FILE *diagFile = NULL;
static wxString origCommandLine = wxT("");
static MyFrame *frame = 0;

static char unipwd[64];

static int lock_db(bool wait);
static void unlock_db(void);

static void exitNow(int status, bool quiet) {
	const char *errors[] = { "Success",
				 "User Cancelled",
				 "Upload Rejected",
				 "Unexpected LoTW Response",
				 "TQSL Error",
				 "TQSLLib Error",
				 "Error opening input file",
				 "Error opening output file",
				 "No QSOs written",
				 "Some QSOs suppressed",
				 "Commmand Syntax Error",
				 "LoTW Connection Failed",
				 "Unknown"
				};
	int stat = status;
	if (stat > TQSL_EXIT_UNKNOWN || stat < 0) stat = TQSL_EXIT_UNKNOWN;
	if (quiet)
		wxLogMessage(wxT("Final Status: %hs (%d)"), errors[stat], status);
	else
		cerr << "Final Status: " << errors[stat] << "(" << status << ")" << endl;
	exit(status);
}

/////////// Application //////////////

class QSLApp : public wxApp {
 public:
	QSLApp();
	virtual ~QSLApp();
	class MyFrame *GUIinit(bool checkUpdates, bool quiet = false);
	bool OnInit();
	virtual int OnRun();
//	virtual wxLog *CreateLogTarget();
};

QSLApp::~QSLApp() {
	wxConfigBase *c = wxConfigBase::Set(0);
	if (c)
		delete c;
	if (diagFile)
		fclose(diagFile);
}

IMPLEMENT_APP(QSLApp)


static int
getCertPassword(char *buf, int bufsiz, tQSL_Cert cert) {
	tqslTrace("getCertPassword", "buf = %lx, bufsiz=%d, cert=%lx", buf, bufsiz, cert);
	char call[TQSL_CALLSIGN_MAX+1] = "";
	int dxcc = 0;
	tqsl_getCertificateCallSign(cert, call, sizeof call);
	tqsl_getCertificateDXCCEntity(cert, &dxcc);
	DXCC dx;
	dx.getByEntity(dxcc);

	wxString message = wxString::Format(wxT("Enter the password to unlock the callsign certificate for\n"
		wxT("%hs -- %hs\n(This is the password you made up when you\ninstalled the callsign certificate.)")),
		call, dx.name());

	wxWindow* top = wxGetApp().GetTopWindow();
	if (!frame->IsQuiet()) {
		frame->Show(true);
		top->SetFocus();
		top->Raise();
	}

	wxString pwd;
	int ret = getPasswordFromUser(pwd, message, wxT("Enter password"), wxT(""), top);
	if (ret != wxID_OK)
		return 1;
	strncpy(buf, pwd.ToUTF8(), bufsiz);
	utf8_to_ucs2(buf, unipwd, sizeof unipwd);
	return 0;
}

class ConvertingDialog : public wxDialog {
 public:
	ConvertingDialog(wxWindow *parent, const char *filename = "");
	void OnCancel(wxCommandEvent&);
	bool running;
	wxStaticText *msg;
 private:
	wxButton *canbut;

	DECLARE_EVENT_TABLE()
};

BEGIN_EVENT_TABLE(ConvertingDialog, wxDialog)
	EVT_BUTTON(TQSL_CD_CANBUT, ConvertingDialog::OnCancel)
END_EVENT_TABLE()

void
ConvertingDialog::OnCancel(wxCommandEvent&) {
	running = false;
	canbut->Enable(FALSE);
}

ConvertingDialog::ConvertingDialog(wxWindow *parent, const char *filename)
	: wxDialog(parent, -1, wxString(wxT("Signing QSO Data"))),
	running(true) {
	wxBoxSizer *sizer = new wxBoxSizer(wxVERTICAL);
	wxString label = wxString(wxT("Converting ")) + wxString::FromUTF8(filename) + wxT(" to TQSL format");
	sizer->Add(new wxStaticText(this, -1, label), 0, wxALL|wxALIGN_CENTER, 10);
	msg = new wxStaticText(this, TQSL_CD_MSG, wxT(" "));
	sizer->Add(msg, 0, wxALL|wxALIGN_LEFT, 10);
	canbut = new wxButton(this, TQSL_CD_CANBUT, wxT("Cancel"));
	sizer->Add(canbut, 0, wxALL|wxEXPAND, 10);
	SetAutoLayout(TRUE);
	SetSizer(sizer);
	sizer->Fit(this);
	sizer->SetSizeHints(this);
	CenterOnParent();
}

#define TQSL_PROG_CANBUT TQSL_ID_LOW+30

DECLARE_EVENT_TYPE(wxEVT_LOGUPLOAD_DONE, -1)
DEFINE_EVENT_TYPE(wxEVT_LOGUPLOAD_DONE)

class UploadDialog : public wxDialog {
 public:
	explicit UploadDialog(wxWindow *parent, wxString title = wxString(wxT("Uploading Signed Data")), wxString label = wxString(wxT("Uploading signed log data...")));
	void OnCancel(wxCommandEvent&);
	void OnDone(wxCommandEvent&);
	int doUpdateProgress(double dltotal, double dlnow, double ultotal, double ulnow);
	static int UpdateProgress(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow) {
		return (reinterpret_cast<UploadDialog*>(clientp))->doUpdateProgress(dltotal, dlnow, ultotal, ulnow);
	}
 private:
	wxButton *canbut;
	wxGauge* progress;
	bool cancelled;
	DECLARE_EVENT_TABLE()
};

BEGIN_EVENT_TABLE(UploadDialog, wxDialog)
	EVT_BUTTON(TQSL_PROG_CANBUT, UploadDialog::OnCancel)
	EVT_COMMAND(wxID_ANY, wxEVT_LOGUPLOAD_DONE, UploadDialog::OnDone)
END_EVENT_TABLE()

void
UploadDialog::OnCancel(wxCommandEvent&) {
	cancelled = true;
	canbut->Enable(false);
}

UploadDialog::UploadDialog(wxWindow *parent, wxString title, wxString label)
	: wxDialog(parent, -1, title), cancelled(false) {
	tqslTrace("UploadDialog::UploadDialog", "parent = %lx", parent);
	wxBoxSizer *sizer = new wxBoxSizer(wxVERTICAL);
	sizer->Add(new wxStaticText(this, -1, label), 0, wxALL|wxALIGN_CENTER, 10);

	progress = new wxGauge(this, -1, 100);
	progress->SetValue(0);
	sizer->Add(progress, 0, wxALL|wxEXPAND);

	canbut = new wxButton(this, TQSL_PROG_CANBUT, wxT("Cancel"));
	sizer->Add(canbut, 0, wxALL|wxEXPAND, 10);
	SetAutoLayout(TRUE);
	SetSizer(sizer);
	sizer->Fit(this);
	sizer->SetSizeHints(this);
	CenterOnParent();
}

void UploadDialog::OnDone(wxCommandEvent&) {
	tqslTrace("UploadDialog::OnDone");
	EndModal(1);
}

int UploadDialog::doUpdateProgress(double dltotal, double dlnow, double ultotal, double ulnow) {
	static double lastDlnow = 0.0;
	if (dlnow != lastDlnow) {
		tqslTrace("UploadDialog::doUpdateProgresss", "dltotal=%f, dlnow=%f, ultotal=%f, ulnow=%f", dltotal, dlnow, ultotal, ulnow);
		lastDlnow = dlnow;
	}
	if (cancelled) return 1;
	if (ultotal > 0.0000001) progress->SetValue(static_cast<int>((100*(ulnow/ultotal))));
	return 0;
}

#define TQSL_DR_START TQSL_ID_LOW+10
#define TQSL_DR_END TQSL_ID_LOW+11
#define TQSL_DR_OK TQSL_ID_LOW+12
#define TQSL_DR_CAN TQSL_ID_LOW+13
#define TQSL_DR_MSG TQSL_ID_LOW+14

class DateRangeDialog : public wxDialog {
 public:
	explicit DateRangeDialog(wxWindow *parent = 0);
	tQSL_Date start, end;
 private:
	void OnOk(wxCommandEvent&);
	void OnCancel(wxCommandEvent&);
	virtual bool TransferDataFromWindow();
	wxTextCtrl *start_tc, *end_tc;
	wxStaticText *msg;
	DECLARE_EVENT_TABLE()
};

BEGIN_EVENT_TABLE(DateRangeDialog, wxDialog)
	EVT_BUTTON(TQSL_DR_OK, DateRangeDialog::OnOk)
	EVT_BUTTON(TQSL_DR_CAN, DateRangeDialog::OnCancel)
END_EVENT_TABLE()

DateRangeDialog::DateRangeDialog(wxWindow *parent) : wxDialog(parent, -1, wxString(wxT("QSO Date Range"))) {
	tqslTrace("DateRangeDialog::DateRangeDialog");
	wxBoxSizer *sizer = new wxBoxSizer(wxVERTICAL);
	sizer->Add(new wxStaticText(this, -1,
		wxT("You may set the starting and/or ending QSO dates\n")
		wxT("in order to select QSOs from the input file.\n\n")
		wxT("QSOs prior to the starting date or after the ending\n")
		wxT("date will not be signed or included in the output file.\n\n")
		wxT("You may leave either date (or both dates) blank.")
	), 0, wxALL|wxALIGN_CENTER, 10);

	wxBoxSizer *hsizer = new wxBoxSizer(wxHORIZONTAL);
	hsizer->Add(new wxStaticText(this, -1, wxT("Start Date (YYYY-MM-DD)")), 0, wxRIGHT, 5);
	start_tc = new wxTextCtrl(this, TQSL_DR_START);
	hsizer->Add(start_tc, 0, 0, 0);
	sizer->Add(hsizer, 0, wxALL|wxALIGN_CENTER, 10);
	hsizer = new wxBoxSizer(wxHORIZONTAL);
	hsizer->Add(new wxStaticText(this, -1, wxT("End Date (YYYY-MM-DD)")), 0, wxRIGHT, 5);
	end_tc = new wxTextCtrl(this, TQSL_DR_END);
	hsizer->Add(end_tc, 0, 0, 0);
	sizer->Add(hsizer, 0, wxALL|wxALIGN_CENTER, 10);
	msg = new wxStaticText(this, TQSL_DR_MSG, wxT(""));
	sizer->Add(msg, 0, wxALL, 5);
	hsizer = new wxBoxSizer(wxHORIZONTAL);
	hsizer->Add(new wxButton(this, TQSL_DR_OK, wxT("OK")), 0, wxRIGHT, 5);
	hsizer->Add(new wxButton(this, TQSL_DR_CAN, wxT("Cancel")), 0, wxLEFT, 10);
	sizer->Add(hsizer, 0, wxALIGN_CENTER|wxALL, 10);
	SetAutoLayout(TRUE);
	SetSizer(sizer);
	sizer->Fit(this);
	sizer->SetSizeHints(this);
	CenterOnParent();
}

bool
DateRangeDialog::TransferDataFromWindow() {
	tqslTrace("DateRangeDialog::TransferDataFromWindow");
	wxString text = start_tc->GetValue();
	tqslTrace("DateRangeDialog::TransferDataFromWindow: start=%s", S(text));
	if (text.Trim() == wxT(""))
		start.year = start.month = start.day = 0;
	else if (tqsl_initDate(&start, text.ToUTF8()) || !tqsl_isDateValid(&start)) {
		msg->SetLabel(wxT("Start date is invalid"));
		return false;
	}
	text = end_tc->GetValue();
	tqslTrace("DateRangeDialog::TransferDataFromWindow: end=%s", S(text));
	if (text.Trim() == wxT(""))
		end.year = end.month = end.day = 0;
	else if (tqsl_initDate(&end, text.ToUTF8()) || !tqsl_isDateValid(&end)) {
		msg->SetLabel(wxT("End date is invalid"));
		return false;
	}
	return true;
}

void
DateRangeDialog::OnOk(wxCommandEvent&) {
	tqslTrace("DateRangeDialog::OnOk");
	if (TransferDataFromWindow())
		EndModal(wxOK);
}

void
DateRangeDialog::OnCancel(wxCommandEvent&) {
	tqslTrace("DateRangeDialog::OnCancel");
	EndModal(wxCANCEL);
}

#define TQSL_DP_OK TQSL_ID_LOW+20
#define TQSL_DP_CAN TQSL_ID_LOW+21
#define TQSL_DP_ALLOW TQSL_ID_LOW+22

class DupesDialog : public wxDialog {
 public:
	DupesDialog(wxWindow *parent = 0, int qso_count = 0, int dupes = 0, int action = TQSL_ACTION_ASK);
 private:
	void OnOk(wxCommandEvent&);
	void OnCancel(wxCommandEvent&);
	void OnAllow(wxCommandEvent&);
	DECLARE_EVENT_TABLE()
};

BEGIN_EVENT_TABLE(DupesDialog, wxDialog)
	EVT_BUTTON(TQSL_DP_OK, DupesDialog::OnOk)
	EVT_BUTTON(TQSL_DP_CAN, DupesDialog::OnCancel)
	EVT_BUTTON(TQSL_DP_ALLOW, DupesDialog::OnAllow)
END_EVENT_TABLE()

DupesDialog::DupesDialog(wxWindow *parent, int qso_count, int dupes, int action)
		: wxDialog(parent, -1, wxString(wxT("Duplicate QSOs Detected")), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE) {
	tqslTrace("DupesDialog::DupesDialog", "qso_count = %d, dupes =%d, action= =%d", qso_count, dupes, action);
	wxBoxSizer *sizer = new wxBoxSizer(wxVERTICAL);
	wxString message;

	if (qso_count == dupes) {
		message = wxString::Format(wxT("This log contains %d QSO(s) which appear ")
		wxT("to have already been signed for upload to LoTW, and no new QSOs.\n\n")
		wxT("Click 'Cancel' to abandon processing this log file (Recommended).\n")
		wxT("Click 'Allow Duplicates' to re-process this ")
		wxT("log while allowing duplicate QSOs."),
			qso_count);

	} else {
		int newq = qso_count - dupes;
		message = wxString::Format(wxT("This log contains %d QSO(s) which appear ")
		wxT("to have already been signed for upload to LoTW, and ")
		wxT("%d QSO%hs new.\n\n")
		wxT("Click 'Exclude duplicates' to sign normally, without the duplicate QSOs (Recommended).\n")
		wxT("Click 'Cancel' to abandon processing this log file.\n")
		wxT("Click 'Allow duplicates' to re-process this log ")
		wxT("while allowing duplicate QSOs."),
			dupes, newq,
			(newq == 1) ? " which is" : "s which are");
	}

	if (action == TQSL_ACTION_UNSPEC) {
		if (qso_count == dupes) {
			message+=
				wxT("\n\nThe log file you are uploading using your QSO Logging system consists entirely of previously uploaded\n")
				wxT("QSOs (duplicates) that create unnecessary work for LoTW. There may be a more recent version of your QSO\n")
				wxT("Logging system that would prevent this. Please check with your QSO Logging system's vendor for an updated version.\n")
				wxT("In the meantime, please note that some loggers may exhibit strange behavior if an option other than 'Allow duplicates'\n")
				wxT("is clicked. Choosing 'Cancel' is usually safe, but a defective logger not checking the status messages reported by TrustedQSL may produce\n")
				wxT("strange (but harmless) behavior such as attempting to upload an empty file or marking all chosen QSOs as 'sent'");
		} else {
			message+=
				wxT("\n\nThe log file you are uploading using your QSO Logging system includes some previously uploaded\n")
				wxT("QSOs (duplicates) that create unnecessary work for LoTW. There may be a more recent version of your\n")
				wxT("QSO Logging system that would prevent this. Please check with your QSO Logging system's vendor for an updated version.\n")
				wxT("In the meantime, please note that some loggers may exhibit strange behavior if an option other than 'Allow duplicates'\n")
				wxT("is clicked. 'Exclude duplicates' is recommended, but a logger that does its own duplicate tracking may incorrectly\n")
				wxT("set the status in this case. A logger that doesn't track duplicates should be unaffected by choosing 'Exclude duplicates'\n")
				wxT("and if it tracks 'QSO sent' status, will correctly mark all selected QSOs as sent - they are in your account even though\n")
				wxT("they would not be in this specific batch\n")
				wxT("Choosing 'Cancel' is usually safe, but a defective logger not checking the status messages reported by TrustedQSL may produce\n")
				wxT("strange (but harmless) behavior such as attempting to upload an empty file or marking all chosen QSOs as 'sent'");
		}
	}
	sizer->Add(new wxStaticText(this, -1, message), 0, wxALL|wxALIGN_CENTER, 10);

	wxBoxSizer *hsizer = new wxBoxSizer(wxHORIZONTAL);
	if (qso_count != dupes)
		hsizer->Add(new wxButton(this, TQSL_DP_OK, wxT("Exclude duplicates")), 0, wxRIGHT, 5);
	hsizer->Add(new wxButton(this, TQSL_DP_CAN, wxT("Cancel")), 0, wxLEFT, 10);
	hsizer->Add(new wxButton(this, TQSL_DP_ALLOW, wxT("Allow duplicates")), 0, wxLEFT, 20);
	sizer->Add(hsizer, 0, wxALIGN_CENTER|wxALL, 10);
	SetAutoLayout(TRUE);
	SetSizer(sizer);
	sizer->Fit(this);
	sizer->SetSizeHints(this);
	CenterOnParent();
}

void
DupesDialog::OnOk(wxCommandEvent&) {
	tqslTrace("DupesDialog::OnOk");
	EndModal(TQSL_DP_OK);
}

void
DupesDialog::OnCancel(wxCommandEvent&) {
	tqslTrace("DupesDialog::OnCancel");
	EndModal(TQSL_DP_CAN);
}

void
DupesDialog::OnAllow(wxCommandEvent&) {
	tqslTrace("DupesDialog::OnAllow");

	if (wxMessageBox(wxT("The only reason to re-sign duplicate QSOs is if a previous upload")
		wxT(" went unprocessed by LoTW, either because it was never uploaded, or there was a server failure\n\n")
		wxT("Are you sure you want to proceed? Click 'No' to review the choices"), wxT("Are you sure?"), wxYES_NO|wxICON_EXCLAMATION, this) == wxYES) {
		EndModal(TQSL_DP_ALLOW);
	}
}

#define TQSL_AE_OK TQSL_ID_LOW+40
#define TQSL_AE_CAN TQSL_ID_LOW+41

class ErrorsDialog : public wxDialog {
 public:
	ErrorsDialog(wxWindow *parent = 0, wxString msg = wxT(""));
 private:
	void OnOk(wxCommandEvent&);
	void OnCancel(wxCommandEvent&);
	DECLARE_EVENT_TABLE()
};

BEGIN_EVENT_TABLE(ErrorsDialog, wxDialog)
	EVT_BUTTON(TQSL_AE_OK, ErrorsDialog::OnOk)
	EVT_BUTTON(TQSL_AE_CAN, ErrorsDialog::OnCancel)
END_EVENT_TABLE()

ErrorsDialog::ErrorsDialog(wxWindow *parent, wxString msg)
		: wxDialog(parent, -1, wxString(wxT("Errors Detected")), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE) {
	tqslTrace("ErrorsDialog::ErrorsDialog", "msg=%s", S(msg));
	wxBoxSizer *sizer = new wxBoxSizer(wxVERTICAL);

	sizer->Add(new wxStaticText(this, -1, msg), 0, wxALL|wxALIGN_CENTER, 10);

	wxBoxSizer *hsizer = new wxBoxSizer(wxHORIZONTAL);
	hsizer->Add(new wxButton(this, TQSL_AE_OK, wxT("Ignore")), 0, wxRIGHT, 5);
	hsizer->Add(new wxButton(this, TQSL_AE_CAN, wxT("Cancel")), 0, wxLEFT, 10);
	sizer->Add(hsizer, 0, wxALIGN_CENTER|wxALL, 10);
	SetAutoLayout(TRUE);
	SetSizer(sizer);
	sizer->Fit(this);
	sizer->SetSizeHints(this);
	CenterOnParent();
}

void
ErrorsDialog::OnOk(wxCommandEvent&) {
	tqslTrace("ErrorsDialog::OnOk");
	EndModal(TQSL_AE_OK);
}

void
ErrorsDialog::OnCancel(wxCommandEvent&) {
	tqslTrace("ErrorsDialog::OnCancel");
	EndModal(TQSL_AE_CAN);
}

static void
init_modes() {
	tqslTrace("init_modes");
	tqsl_clearADIFModes();
	wxConfig *config = reinterpret_cast<wxConfig *>(wxConfig::Get());
	long cookie;
	wxString key, value;
	vector<wxString> badModes;
	config->SetPath(wxT("/modeMap"));
	bool stat = config->GetFirstEntry(key, cookie);
	while (stat) {
		value = config->Read(key, wxT(""));
		bool newMode = true;
		int numModes;
		if (tqsl_getNumMode(&numModes) == 0) {
			for (int i = 0; i < numModes; i++) {
				const char *modestr;
				if (tqsl_getMode(i, &modestr, NULL) == 0) {
					if (strcasecmp(key.ToUTF8(), modestr) == 0) {
						wxLogWarning(wxT("Your custom mode map %s conflicts with the standard mode definition for %hs and was deleted."), key.c_str(), modestr);
						newMode = false;
						badModes.push_back(key);
						break;
					}
				}
			}
		}
		if (newMode)
			tqsl_setADIFMode(key.ToUTF8(), value.ToUTF8());
		stat = config->GetNextEntry(key, cookie);
	}
	// Delete the conflicting entries
	for (int i = 0; i < static_cast<int>(badModes.size()); i++) {
		config->DeleteEntry(badModes[i]);
	}
	config->SetPath(wxT("/"));
}

static void
init_contests() {
	tqslTrace("init_contests");
	tqsl_clearCabrilloMap();
	wxConfig *config = reinterpret_cast<wxConfig *>(wxConfig::Get());
	long cookie;
	wxString key, value;
	config->SetPath(wxT("/cabrilloMap"));
	bool stat = config->GetFirstEntry(key, cookie);
	while (stat) {
		value = config->Read(key, wxT(""));
		int contest_type = strtol(value.ToUTF8(), NULL, 10);
		int callsign_field = strtol(value.AfterFirst(';').ToUTF8(), NULL, 10);
		tqsl_setCabrilloMapEntry(key.ToUTF8(), callsign_field, contest_type);
		stat = config->GetNextEntry(key, cookie);
	}
	config->SetPath(wxT("/"));
}

static void
check_tqsl_error(int rval) {
	if (rval == 0)
		return;
	tqslTrace("check_tqsl_error", "rval=%d", rval);
	const char *msg = tqsl_getErrorString();
	tqslTrace("check_tqsl_error", "msg=%s", msg);
	throw TQSLException(msg);
}

static tQSL_Cert *certlist = 0;
static int ncerts;

static void
free_certlist() {
	tqslTrace("free_certlist");
	if (certlist) {
		for (int i = 0; i < ncerts; i++)
			tqsl_freeCertificate(certlist[i]);
		certlist = 0;
	}
	ncerts = 0;
}

static void
get_certlist(string callsign, int dxcc, bool expired, bool superceded, bool withkeys) {
	tqslTrace("get_certlist", "callsign=%s, dxcc=%d, expired=%d, superceded=%d withkeys=%d", callsign.c_str(), dxcc, expired, superceded, withkeys);
	free_certlist();
	int select = 0;
	if (expired) select |= TQSL_SELECT_CERT_EXPIRED;
	if (superceded) select |= TQSL_SELECT_CERT_SUPERCEDED;
	if (withkeys) select |= TQSL_SELECT_CERT_WITHKEYS;
	tqsl_selectCertificates(&certlist, &ncerts,
		(callsign == "") ? 0 : callsign.c_str(), dxcc, 0, 0, select);
}

class LogList : public wxLog {
 public:
	explicit LogList(MyFrame *frame) : wxLog(), _frame(frame) {}
	virtual void DoLogString(const wxChar *szString, time_t t);
 private:
	MyFrame *_frame;
};

void LogList::DoLogString(const wxChar *szString, time_t) {
	wxTextCtrl *_logwin = 0;

	if (diagFile)  {
#ifdef _WIN32
		fprintf(diagFile, "%hs\n", szString);
#else
//		const char *cstr = wxString(szString).ToUTF8();
//		fprintf(diagFile, "%s\n", cstr);
		fprintf(diagFile, "%ls\n", szString);
#endif
	}
	if (wxString(szString).StartsWith(wxT("Debug:")))
		return;
	if (wxString(szString).StartsWith(wxT("Error: Unable to open requested HTML document:")))
		return;
	if (_frame != 0)
		_logwin = _frame->logwin;
	if (_logwin == 0) {
#ifdef _WIN32
		cerr << szString << endl;
#else
		fprintf(stderr, "%ls\n", szString);
#endif
		return;
	}
	_logwin->AppendText(szString);
	_logwin->AppendText(wxT("\n"));
}

class LogStderr : public wxLog {
 public:
	LogStderr(void) : wxLog() {}
	virtual void DoLogString(const wxChar *szString, time_t t);
};

void LogStderr::DoLogString(const wxChar *szString, time_t) {
	if (diagFile) {
#ifdef _WIN32
		fprintf(diagFile, "%hs\n", szString);
#else
		fprintf(diagFile, "%ls\n", szString);
//		const char *cstr = wxString(szString).ToUTF8();
//		fprintf(diagFile, "%s\n", cstr);
#endif
	}
	if (wxString(szString).StartsWith(wxT("Debug:")))
		return;
#ifdef _WIN32
	cerr << szString << endl;
#else
	fprintf(stderr, "%ls\n", szString);
#endif
	return;
}

BEGIN_EVENT_TABLE(MyFrame, wxFrame)
	EVT_MENU(tm_s_add, MyFrame::AddStationLocation)
	EVT_BUTTON(tl_AddLoc, MyFrame::AddStationLocation)
	EVT_MENU(tm_s_edit, MyFrame::EditStationLocation)
	EVT_BUTTON(tl_EditLoc, MyFrame::EditStationLocation)
	EVT_MENU(tm_f_new, MyFrame::EnterQSOData)
	EVT_BUTTON(tl_Edit, MyFrame::EnterQSOData)
	EVT_MENU(tm_f_edit, MyFrame::EditQSOData)
	EVT_MENU(tm_f_import_compress, MyFrame::ImportQSODataFile)
	EVT_BUTTON(tl_Save, MyFrame::ImportQSODataFile)
	EVT_MENU(tm_f_upload, MyFrame::UploadQSODataFile)
	EVT_BUTTON(tl_Upload, MyFrame::UploadQSODataFile)
	EVT_MENU(tm_f_exit, MyFrame::DoExit)
	EVT_MENU(tm_f_preferences, MyFrame::OnPreferences)
	EVT_MENU(tm_f_loadconfig, MyFrame::OnLoadConfig)
	EVT_MENU(tm_f_saveconfig, MyFrame::OnSaveConfig)
	EVT_MENU(tm_h_contents, MyFrame::OnHelpContents)
	EVT_MENU(tm_h_about, MyFrame::OnHelpAbout)
	EVT_MENU(tm_f_diag, MyFrame::OnHelpDiagnose)

	EVT_MENU(tm_h_update, MyFrame::CheckForUpdates)

	EVT_CLOSE(MyFrame::OnExit)

	EVT_MENU(tc_CRQWizard, MyFrame::CRQWizard)
	EVT_MENU(tc_c_New, MyFrame::CRQWizard)
	EVT_MENU(tc_c_Load, MyFrame::OnLoadCertificateFile)
	EVT_BUTTON(tc_Load, MyFrame::OnLoadCertificateFile)
	EVT_MENU(tc_c_Properties, MyFrame::OnCertProperties)
	EVT_BUTTON(tc_CertProp, MyFrame::OnCertProperties)
	EVT_MENU(tc_c_Export, MyFrame::OnCertExport)
	EVT_BUTTON(tc_CertSave, MyFrame::OnCertExport)
	EVT_MENU(tc_c_Delete, MyFrame::OnCertDelete)
//	EVT_MENU(tc_c_Import, MyFrame::OnCertImport)
//	EVT_MENU(tc_c_Sign, MyFrame::OnSign)
	EVT_MENU(tc_c_Renew, MyFrame::CRQWizardRenew)
	EVT_BUTTON(tc_CertRenew, MyFrame::CRQWizardRenew)
	EVT_MENU(tc_h_Contents, MyFrame::OnHelpContents)
	EVT_MENU(tc_h_About, MyFrame::OnHelpAbout)
	EVT_MENU(tl_c_Properties, MyFrame::OnLocProperties)
	EVT_MENU(tm_s_Properties, MyFrame::OnLocProperties)
	EVT_BUTTON(tl_PropLoc, MyFrame::OnLocProperties)
	EVT_MENU(tl_c_Delete, MyFrame::OnLocDelete)
	EVT_BUTTON(tl_DeleteLoc, MyFrame::OnLocDelete)
	EVT_MENU(tl_c_Edit, MyFrame::OnLocEdit)
	EVT_BUTTON(tl_Login, MyFrame::OnLoginToLogbook)
	EVT_TREE_SEL_CHANGED(tc_CertTree, MyFrame::OnCertTreeSel)
	EVT_TREE_SEL_CHANGED(tc_LocTree, MyFrame::OnLocTreeSel)

	EVT_MENU(bg_updateCheck, MyFrame::OnUpdateCheckDone)
	EVT_MENU(bg_expiring, MyFrame::OnExpiredCertFound)

END_EVENT_TABLE()

void
MyFrame::OnExit(TQ_WXCLOSEEVENT& WXUNUSED(event)) {
	int x, y, w, h;
	// Don't save window size/position if minimized or too small
	wxConfig *config = reinterpret_cast<wxConfig *>(wxConfig::Get());
	if (!IsIconized()) {
		GetPosition(&x, &y);
		GetSize(&w, &h);
		if (w >= MAIN_WINDOW_MIN_WIDTH && h >= MAIN_WINDOW_MIN_HEIGHT) {
			config->Write(wxT("MainWindowX"), x);
			config->Write(wxT("MainWindowY"), y);
			config->Write(wxT("MainWindowWidth"), w);
			config->Write(wxT("MainWindowHeight"), h);
			config->Flush(false);
		}
	}
	bool ab;
	config->Read(wxT("AutoBackup"), &ab, DEFAULT_AUTO_BACKUP);
	if (ab) {
		wxString bdir = config->Read(wxT("BackupFolder"), wxString::FromUTF8(tQSL_BaseDir));
#ifdef _WIN32
		bdir += wxT("\\tqslconfig.tbk");
#else
		bdir += wxT("/tqslconfig.tbk");
#endif
		BackupConfig(bdir, true);
	}
	Destroy();		// close the window
}

void
MyFrame::DoExit(wxCommandEvent& WXUNUSED(event)) {
	Close();
	Destroy();
}

static wxSemaphore *updateLocker;

class UpdateThread : public wxThread {
 public:
	UpdateThread(MyFrame *frame, bool silent, bool noGUI) : wxThread(wxTHREAD_DETACHED) {
		_frame = frame;
		_silent = silent;
		_noGUI = noGUI;
	}
	virtual void *Entry() {
		_frame->DoCheckForUpdates(_silent, _noGUI);
		updateLocker->Post();
		return NULL;
	}
 private:
	MyFrame *_frame;
	bool _silent;
	bool _noGUI;
};

void
MyFrame::DoUpdateCheck(bool silent, bool noGUI) {
	tqslTrace("MyFrame::DoUpdateCheck", "silent=%d noGUI=%d", silent, noGUI);
	//check for updates
	if (!noGUI) {
		wxBeginBusyCursor();
		wxSafeYield();
		wxLogMessage(wxT("Checking for TQSL updates..."));
		wxSafeYield();
	}
	updateLocker = new wxSemaphore(0, 1);		// One waiter
	UpdateThread* thread = new UpdateThread(this, silent, noGUI);
	thread->Create();
	wxSafeYield();
	thread->Run();
	wxSafeYield();
	while (updateLocker->WaitTimeout(200) == wxSEMA_TIMEOUT) {
		wxSafeYield();
	}
	delete updateLocker;
	if (!noGUI) {
		wxString val = logwin->GetValue();
		val.Replace(wxT("Checking for TQSL updates...\n"), wxT(""));
		logwin->SetValue(val);		// Clear the checking message
		// Refresh the cert tree in case any new info on expires/supercedes
		cert_tree->Build(CERTLIST_FLAGS);
		CertTreeReset();
		wxEndBusyCursor();
	}
}

MyFrame::MyFrame(const wxString& title, int x, int y, int w, int h, bool checkUpdates, bool quiet)
	: wxFrame(0, -1, title, wxPoint(x, y), wxSize(w, h)) {
	_quiet = quiet;

	DocPaths docpaths(wxT("tqslapp"));
	wxBitmap savebm(save_xpm);
	wxBitmap uploadbm(upload_xpm);
	wxBitmap upload_disbm(upload_dis_xpm);
	wxBitmap file_editbm(file_edit_xpm);
	wxBitmap file_edit_disbm(file_edit_dis_xpm);
	wxBitmap locaddbm(loc_add_xpm);
	wxBitmap locadd_disbm(loc_add_dis_xpm);
	wxBitmap editbm(edit_xpm);
	wxBitmap edit_disbm(edit_dis_xpm);
	wxBitmap deletebm(delete_xpm);
	wxBitmap delete_disbm(delete_dis_xpm);
	wxBitmap downloadbm(download_xpm);
	wxBitmap download_disbm(download_dis_xpm);
	wxBitmap propertiesbm(properties_xpm);
	wxBitmap properties_disbm(properties_dis_xpm);
	wxBitmap importbm(import_xpm);
	wxBitmap lotwbm(lotw_xpm);
	loc_edit_button = NULL;
	cert_save_label = NULL;
	req = NULL;
	curlReq = NULL;
	curlLogFile = NULL;

	// File menu
	file_menu = new wxMenu;
	file_menu->Append(tm_f_upload, wxT("Sign and &upload ADIF or Cabrillo File..."));
	file_menu->Append(tm_f_import_compress, wxT("&Sign and save ADIF or Cabrillo file..."));
	file_menu->AppendSeparator();
	file_menu->Append(tm_f_saveconfig, wxT("&Backup Station Locations, Certificates, and Preferences..."));
	file_menu->Append(tm_f_loadconfig, wxT("&Restore Station Locations, Certificates, and Preferences..."));
	file_menu->AppendSeparator();
	file_menu->Append(tm_f_new, wxT("Create &New ADIF file..."));
	file_menu->Append(tm_f_edit, wxT("&Edit existing ADIF file..."));
	file_menu->AppendSeparator();
#ifdef __WXMAC__	// On Mac, Preferences not on File menu
	file_menu->Append(tm_f_preferences, wxT("&Preferences..."));
#else
	file_menu->Append(tm_f_preferences, wxT("Display or Modify &Preferences..."));
#endif
	file_menu->AppendSeparator();
	file_menu->AppendCheckItem(tm_f_diag, wxT("Dia&gnostic Mode"));
	file_menu->Check(tm_f_diag, false);
#ifndef __WXMAC__	// On Mac, Exit not on File menu
	file_menu->AppendSeparator();
#endif
	file_menu->Append(tm_f_exit, wxT("E&xit TQSL\tAlt-X"));

	cert_menu = makeCertificateMenu(false);
	// Station menu
	stn_menu = new wxMenu;
	stn_menu->Append(tm_s_Properties, wxT("&Display Station Location Properties"));
	stn_menu->Enable(tm_s_Properties, false);
	stn_menu->Append(tm_s_edit, wxT("&Edit Station Location"));
	stn_menu->Append(tm_s_add, wxT("&Add Station Location"));

	// Help menu
	help = new wxHtmlHelpController(wxHF_DEFAULT_STYLE | wxHF_OPEN_FILES);
	help_menu = new wxMenu;
	help->UseConfig(wxConfig::Get());
	wxString hhp = docpaths.FindAbsoluteValidPath(wxT("tqslapp.hhp"));
	if (wxFileNameFromPath(hhp) != wxT("")) {
		if (help->AddBook(hhp))
#ifdef __WXMAC__
		help_menu->Append(tm_h_contents, wxT("&Contents"));
#else
		help_menu->Append(tm_h_contents, wxT("Display &Documentation"));
		help_menu->AppendSeparator();
#endif
	}

	help_menu->Append(tm_h_update, wxT("Check for &Updates..."));

	help_menu->Append(tm_h_about, wxT("&About"));
	// Main menu
	wxMenuBar *menu_bar = new wxMenuBar;
	menu_bar->Append(file_menu, wxT("&File"));
	menu_bar->Append(stn_menu, wxT("&Station Location"));
	menu_bar->Append(cert_menu, wxT("Callsign &Certificate"));
	menu_bar->Append(help_menu, wxT("&Help"));

	SetMenuBar(menu_bar);

	wxPanel* topPanel = new wxPanel(this);
	wxBoxSizer* topSizer = new wxBoxSizer(wxVERTICAL);
	topPanel->SetSizer(topSizer);

	// Log operations

	//topSizer->Add(new wxStaticText(topPanel, -1, wxT("")), 0, wxEXPAND | wxALL, 1);
	topSizer->AddSpacer(10);

	wxNotebook* notebook = new wxNotebook(topPanel, -1, wxDefaultPosition, wxDefaultSize, wxNB_TOP /* | wxNB_FIXEDWIDTH*/, wxT("Log Operations"));

	topSizer->Add(notebook, 50, wxEXPAND | wxALL, 1);

	topSizer->Add(new wxStaticText(topPanel, -1, wxT("Status Log")), 0, wxEXPAND | wxALL, 1);

	logwin = new wxTextCtrl(topPanel, -1, wxT(""), wxDefaultPosition, wxSize(400, 200),
		wxTE_MULTILINE|wxTE_READONLY);
	topSizer->Add(logwin, 50, wxEXPAND | wxALL, 1);

	wxPanel* buttons = new wxPanel(notebook, -1);
	buttons->SetBackgroundColour(wxColour(255, 255, 255));

	wxBoxSizer* bsizer = new wxBoxSizer(wxVERTICAL);
	buttons->SetSizer(bsizer);

	wxPanel* b1Panel = new wxPanel(buttons);
	b1Panel->SetBackgroundColour(wxColour(255, 255, 255));
	wxBoxSizer* b1sizer = new wxBoxSizer(wxHORIZONTAL);
	b1Panel->SetSizer(b1sizer);

	wxBitmapButton *up = new wxBitmapButton(b1Panel, tl_Upload, uploadbm);
	up->SetBitmapDisabled(upload_disbm);
	b1sizer->Add(up, 0, wxALL, 1);
	b1sizer->Add(new wxStaticText(b1Panel, -1, wxT("\nSign a log and upload it automatically to LoTW")), 1, wxALL, 1);
	bsizer->Add(b1Panel, 0, wxALL, 1);

	wxPanel* b2Panel = new wxPanel(buttons);
	wxBoxSizer* b2sizer = new wxBoxSizer(wxHORIZONTAL);
	b2Panel->SetBackgroundColour(wxColour(255, 255, 255));
	b2Panel->SetSizer(b2sizer);
	b2sizer->Add(new wxBitmapButton(b2Panel, tl_Save, savebm), 0, wxALL, 1);
	b2sizer->Add(new wxStaticText(b2Panel, -1, wxT("\nSign a log and save it for uploading later")), 1, wxALL, 1);
	bsizer->Add(b2Panel, 0, wxALL, 1);

	wxPanel* b3Panel = new wxPanel(buttons);
	wxBoxSizer* b3sizer = new wxBoxSizer(wxHORIZONTAL);
	b3Panel->SetBackgroundColour(wxColour(255, 255, 255));
	b3Panel->SetSizer(b3sizer);
	wxBitmapButton *fed = new wxBitmapButton(b3Panel, tl_Edit, file_editbm);
	fed->SetBitmapDisabled(file_edit_disbm);
	b3sizer->Add(fed, 0, wxALL, 1);
	b3sizer->Add(new wxStaticText(b3Panel, -1, wxT("\nCreate an ADIF file for signing and uploading")), 1, wxALL, 1);
	bsizer->Add(b3Panel, 0, wxALL, 1);

	wxPanel* b4Panel = new wxPanel(buttons);
	wxBoxSizer* b4sizer = new wxBoxSizer(wxHORIZONTAL);
	b4Panel->SetBackgroundColour(wxColour(255, 255, 255));
	b4Panel->SetSizer(b4sizer);
	b4sizer->Add(new wxBitmapButton(b4Panel, tl_Login, lotwbm), 0, wxALL, 1);
	b4sizer->Add(new wxStaticText(b4Panel, -1, wxT("\nLog in to the Logbook of the World Site")), 1, wxALL, 1);
	bsizer->Add(b4Panel, 0, wxALL, 1);

	notebook->AddPage(buttons, wxT("Log Operations"));

//	notebook->InvalidateBestSize();
//	logwin->FitInside();

	// Location tab

	wxPanel* loctab = new wxPanel(notebook, -1);

	wxBoxSizer* locsizer = new wxBoxSizer(wxHORIZONTAL);
	loctab->SetSizer(locsizer);

	wxPanel* locgrid = new wxPanel(loctab, -1);
	locgrid->SetBackgroundColour(wxColour(255, 255, 255));
	wxBoxSizer* lgsizer = new wxBoxSizer(wxVERTICAL);
	locgrid->SetSizer(lgsizer);

	loc_tree = new LocTree(locgrid, tc_LocTree, wxDefaultPosition,
		wxDefaultSize, wxTR_DEFAULT_STYLE | wxBORDER_NONE);

	loc_tree->SetBackgroundColour(wxColour(255, 255, 255));
	loc_tree->Build();
	LocTreeReset();
	lgsizer->Add(loc_tree, 1, wxEXPAND);

	loc_select_label = new wxStaticText(locgrid, -1, wxT("\nSelect a Station Location to process      "));
	lgsizer->Add(loc_select_label, 0, wxALL, 1);

	locsizer->Add(locgrid, 50, wxEXPAND);

	wxStaticLine *locsep =new wxStaticLine(loctab, -1, wxDefaultPosition, wxSize(2, -1), wxLI_VERTICAL);
	locsizer->Add(locsep, 0, wxEXPAND);

	wxPanel* lbuttons = new wxPanel(loctab, -1);
	lbuttons->SetBackgroundColour(wxColour(255, 255, 255));
	locsizer->Add(lbuttons, 50, wxEXPAND);
	wxBoxSizer* lbsizer = new wxBoxSizer(wxVERTICAL);
	lbuttons->SetSizer(lbsizer);

	wxPanel* lb1Panel = new wxPanel(lbuttons);
	lb1Panel->SetBackgroundColour(wxColour(255, 255, 255));
	wxBoxSizer* lb1sizer = new wxBoxSizer(wxHORIZONTAL);
	lb1Panel->SetSizer(lb1sizer);

	loc_add_button = new wxBitmapButton(lb1Panel, tl_AddLoc, locaddbm);
	loc_add_button->SetBitmapDisabled(locadd_disbm);
	lb1sizer->Add(loc_add_button, 0, wxALL, 1);
	// Note - the doubling below is to size the label to allow the control to stretch later
	loc_add_label = new wxStaticText(lb1Panel, -1, wxT("\nCreate a new Station LocationCreate a new Station\n"));
	lb1sizer->Add(loc_add_label, 1, wxFIXED_MINSIZE | wxALL, 1);
	lbsizer->Add(lb1Panel, 1, wxALL, 1);
	int tw, th;
	loc_add_label->GetSize(&tw, &th);
	loc_add_label->SetLabel(wxT("\nCreate a new Station Location"));

	wxPanel* lb2Panel = new wxPanel(lbuttons);
	lb2Panel->SetBackgroundColour(wxColour(255, 255, 255));
	wxBoxSizer* lb2sizer = new wxBoxSizer(wxHORIZONTAL);
	lb2Panel->SetSizer(lb2sizer);

	loc_edit_button = new wxBitmapButton(lb2Panel, tl_EditLoc, editbm);
	loc_edit_button->SetBitmapDisabled(edit_disbm);
	loc_edit_button->Enable(false);
	lb2sizer->Add(loc_edit_button, 0, wxALL, 1);
	loc_edit_label = new wxStaticText(lb2Panel, -1, wxT("\nEdit a Station Location"), wxDefaultPosition, wxSize(tw, th));
	lb2sizer->Add(loc_edit_label, 1, wxFIXED_MINSIZE | wxALL, 1);
	lbsizer->Add(lb2Panel, 1, wxALL, 1);

	wxPanel* lb3Panel = new wxPanel(lbuttons);
	lb3Panel->SetBackgroundColour(wxColour(255, 255, 255));
	wxBoxSizer* lb3sizer = new wxBoxSizer(wxHORIZONTAL);
	lb3Panel->SetSizer(lb3sizer);

	loc_delete_button = new wxBitmapButton(lb3Panel, tl_DeleteLoc, deletebm);
	loc_delete_button->SetBitmapDisabled(delete_disbm);
	loc_delete_button->Enable(false);
	lb3sizer->Add(loc_delete_button, 0, wxALL, 1);
	loc_delete_label = new wxStaticText(lb3Panel, -1, wxT("\nDelete a Station Location"), wxDefaultPosition, wxSize(tw, th));
	lb3sizer->Add(loc_delete_label, 1, wxFIXED_MINSIZE | wxALL, 1);
	lbsizer->Add(lb3Panel, 1, wxALL, 1);

	wxPanel* lb4Panel = new wxPanel(lbuttons);
	lb4Panel->SetBackgroundColour(wxColour(255, 255, 255));
	wxBoxSizer* lb4sizer = new wxBoxSizer(wxHORIZONTAL);
	lb4Panel->SetSizer(lb4sizer);

	loc_prop_button = new wxBitmapButton(lb4Panel, tl_PropLoc, propertiesbm);
	loc_prop_button->SetBitmapDisabled(properties_disbm);
	loc_prop_button->Enable(false);
	lb4sizer->Add(loc_prop_button, 0, wxALL, 1);
	loc_prop_label = new wxStaticText(lb4Panel, -1, wxT("\nDisplay Station Location Properties"), wxDefaultPosition, wxSize(tw, th));
	lb4sizer->Add(loc_prop_label, 1, wxFIXED_MINSIZE | wxALL, 1);
	lbsizer->Add(lb4Panel, 1, wxALL, 1);

	notebook->AddPage(loctab, wxT("Station Locations"));

	// Certificates tab

	wxPanel* certtab = new wxPanel(notebook, -1);

	wxBoxSizer* certsizer = new wxBoxSizer(wxHORIZONTAL);
	certtab->SetSizer(certsizer);

	wxPanel* certgrid = new wxPanel(certtab, -1);
	certgrid->SetBackgroundColour(wxColour(255, 255, 255));
	wxBoxSizer* cgsizer = new wxBoxSizer(wxVERTICAL);
	certgrid->SetSizer(cgsizer);

	cert_tree = new CertTree(certgrid, tc_CertTree, wxDefaultPosition,
		wxDefaultSize, wxTR_DEFAULT_STYLE | wxBORDER_NONE); //wxTR_HAS_BUTTONS | wxSUNKEN_BORDER);

	cert_tree->SetBackgroundColour(wxColour(255, 255, 255));
	cgsizer->Add(cert_tree, 1, wxEXPAND);

	cert_select_label = new wxStaticText(certgrid, -1, wxT("\nSelect a Callsign Certificate to process"));
	cgsizer->Add(cert_select_label, 0, wxALL, 1);

	certsizer->Add(certgrid, 50, wxEXPAND);

	wxStaticLine *certsep =new wxStaticLine(certtab, -1, wxDefaultPosition, wxSize(2, -1), wxLI_VERTICAL);
	certsizer->Add(certsep, 0, wxEXPAND);

	wxPanel* cbuttons = new wxPanel(certtab, -1);
	cbuttons->SetBackgroundColour(wxColour(255, 255, 255));
	certsizer->Add(cbuttons, 50, wxEXPAND, 0);

	wxBoxSizer* cbsizer = new wxBoxSizer(wxVERTICAL);
	cbuttons->SetSizer(cbsizer);

	wxPanel* cb1Panel = new wxPanel(cbuttons);
	cb1Panel->SetBackgroundColour(wxColour(255, 255, 255));
	wxBoxSizer* cb1sizer = new wxBoxSizer(wxHORIZONTAL);
	cb1Panel->SetSizer(cb1sizer);

	cert_load_button = new wxBitmapButton(cb1Panel, tc_Load, importbm);
	cert_load_button->SetBitmapDisabled(delete_disbm);
	cb1sizer->Add(cert_load_button, 0, wxALL, 1);
	cert_load_label = new wxStaticText(cb1Panel, -1, wxT("\nLoad a Callsign Certificate"), wxDefaultPosition, wxSize(tw, th));
	cb1sizer->Add(cert_load_label, 1, wxFIXED_MINSIZE | wxALL, 1);
	cbsizer->Add(cb1Panel, 1, wxALL, 1);

	wxPanel* cb2Panel = new wxPanel(cbuttons);
	cb2Panel->SetBackgroundColour(wxColour(255, 255, 255));
	wxBoxSizer* cb2sizer = new wxBoxSizer(wxHORIZONTAL);
	cb2Panel->SetSizer(cb2sizer);

	cert_save_button = new wxBitmapButton(cb2Panel, tc_CertSave, downloadbm);
	cert_save_button->SetBitmapDisabled(download_disbm);
	cert_save_button->Enable(false);
	cb2sizer->Add(cert_save_button, 0, wxALL, 1);
	cert_save_label = new wxStaticText(cb2Panel, -1, wxT("\nSave a Callsign Certificate"), wxDefaultPosition, wxSize(tw, th));
	cb2sizer->Add(cert_save_label, 1, wxFIXED_MINSIZE | wxALL, 1);
	cbsizer->Add(cb2Panel, 1, wxALL, 1);

	wxPanel* cb3Panel = new wxPanel(cbuttons);
	cb3Panel->SetBackgroundColour(wxColour(255, 255, 255));
	wxBoxSizer* cb3sizer = new wxBoxSizer(wxHORIZONTAL);
	cb3Panel->SetSizer(cb3sizer);

	cert_renew_button = new wxBitmapButton(cb3Panel, tc_CertRenew, uploadbm);
	cert_renew_button->SetBitmapDisabled(upload_disbm);
	cert_renew_button->Enable(false);
	cb3sizer->Add(cert_renew_button, 0, wxALL, 1);
	cert_renew_label = new wxStaticText(cb3Panel, -1, wxT("\nRenew a Callsign Certificate"), wxDefaultPosition, wxSize(tw, th));
	cb3sizer->Add(cert_renew_label, 1, wxFIXED_MINSIZE | wxALL, 1);
	cbsizer->Add(cb3Panel, 1, wxALL, 1);

	wxPanel* cb4Panel = new wxPanel(cbuttons);
	cb4Panel->SetBackgroundColour(wxColour(255, 255, 255));
	wxBoxSizer* cb4sizer = new wxBoxSizer(wxHORIZONTAL);
	cb4Panel->SetSizer(cb4sizer);

	cert_prop_button = new wxBitmapButton(cb4Panel, tc_CertProp, propertiesbm);
	cert_prop_button->SetBitmapDisabled(properties_disbm);
	cert_prop_button->Enable(false);
	cb4sizer->Add(cert_prop_button, 0, wxALL, 1);
	cert_prop_label = new wxStaticText(cb4Panel, -1, wxT("\nDisplay a Callsign Certificate's Properties"), wxDefaultPosition, wxSize(tw, th));
	cb4sizer->Add(cert_prop_label, 1, wxFIXED_MINSIZE | wxALL, 1);
	cbsizer->Add(cb4Panel, 1, wxALL, 1);

	notebook->AddPage(certtab, wxT("Callsign Certificates"));

	//app icon
	SetIcon(wxIcon(key_xpm));

	if (checkUpdates) {
		LogList *log = new LogList(this);
		wxLog::SetActiveTarget(log);
	}
}

static wxString
run_station_wizard(wxWindow *parent, tQSL_Location loc, wxHtmlHelpController *help = 0,
	bool expired = false, wxString title = wxT("Add Station Location"), wxString dataname = wxT(""), wxString callsign = wxT("")) {
	tqslTrace("run_station_wizard", "loc=%lx, expired=%d, title=%s, dataname=%s, callsign=%s", loc, expired, S(title), S(dataname), S(callsign));
	wxString rval(wxT(""));
	get_certlist("", 0, expired, false, false);
	if (ncerts == 0)
		throw TQSLException("No certificates available");
	TQSLWizard *wiz = new TQSLWizard(loc, parent, help, title, expired);
	wiz->SetDefaultCallsign(callsign);
	wiz->GetPage(true);
	TQSLWizCertPage *cpage = reinterpret_cast<TQSLWizCertPage*>(wiz->GetPage());
	if (cpage && !callsign.IsEmpty())
		cpage->UpdateFields(0);
	TQSLWizPage *page = wiz->GetPage();
	if (page == 0)
		throw TQSLException("Error getting first wizard page");
	wiz->AdjustSize();
	// Note: If dynamically created pages are larger than the pages already
	// created (the initial page and the final page), the wizard will need to
	// be resized, but we don't presently have that happening. (The final
	// page is larger than all expected dynamic pages.)
	bool okay = wiz->RunWizard(page);
	rval = wiz->GetLocationName();
	wiz->Destroy();
	if (!okay)
		return rval;
	wxCharBuffer locname = rval.ToUTF8();
	check_tqsl_error(tqsl_setStationLocationCaptureName(loc, locname.data()));
	check_tqsl_error(tqsl_saveStationLocationCapture(loc, 1));
	return rval;
}

void
MyFrame::OnHelpContents(wxCommandEvent& WXUNUSED(event)) {
	help->Display(wxT("main.htm"));
}

// Return the "About" string
//
static wxString getAbout() {
	wxString msg = wxT("TQSL V") wxT(VERSION) wxT(" build ") wxT(BUILD) wxT("\n(c) 2001-2014\nAmerican Radio Relay League\n\n");
	int major, minor;
	if (tqsl_getVersion(&major, &minor))
		wxLogError(wxT("%hs"), tqsl_getErrorString());
	else
		msg += wxString::Format(wxT("TrustedQSL library V%d.%d\n"), major, minor);
	if (tqsl_getConfigVersion(&major, &minor))
		wxLogError(wxT("%hs"), tqsl_getErrorString());
	else
		msg += wxString::Format(wxT("\nConfiguration data V%d.%d\n\n"), major, minor);
	msg += wxVERSION_STRING;
#ifdef wxUSE_UNICODE
	if (wxUSE_UNICODE)
		msg += wxT(" (Unicode)");
#endif
	msg+=wxString::Format(wxT("\nlibcurl V%hs\n"), LIBCURL_VERSION);
	msg+=wxString::Format(wxT("%hs\n"), OPENSSL_VERSION_TEXT);
	msg+=wxString::Format(wxT("zlib V%hs\n"), ZLIB_VERSION);
	msg+=wxString::Format(wxT("%hs"), DB_VERSION_STRING);
	return msg;
}

void
MyFrame::OnHelpAbout(wxCommandEvent& WXUNUSED(event)) {
	wxMessageBox(getAbout(), wxT("About"), wxOK|wxCENTRE|wxICON_INFORMATION, this);
}

void
MyFrame::OnHelpDiagnose(wxCommandEvent& event) {
	wxString s_fname;

	if (diagFile) {
		file_menu->Check(tm_f_diag, false);
		fclose(diagFile);
		diagFile = NULL;
		wxMessageBox(wxT("Diagnostic log closed"), wxT("Diagnostics"), wxOK|wxCENTRE|wxICON_INFORMATION, this);
		return;
	}
	s_fname = wxFileSelector(wxT("Log File"), wxT(""), wxT("tqsldiag.log"), wxT("log"),
			wxT("Log files (*.log)|*.log|All files (*.*)|*.*"),
			wxFD_SAVE|wxFD_OVERWRITE_PROMPT, this);
	if (s_fname == wxT("")) {
		file_menu->Check(tm_f_diag, false); //would be better to not check at all, but no, apparently that's a crazy thing to want
		return;
	}
	diagFile = fopen(tqslName(s_fname), "wb");
	if (!diagFile) {
		wxString errmsg = wxString::Format(wxT("Error opening diagnostic log %s: %hs"), s_fname.c_str(), strerror(errno));
		wxMessageBox(errmsg, wxT("Log File Error"), wxOK|wxICON_EXCLAMATION);
		return;
	}
	file_menu->Check(tm_f_diag, true);
	wxString about = getAbout();
	fprintf(diagFile, "TQSL Diagnostics\n%s\n\n", (const char *)about.ToUTF8());
	fprintf(diagFile, "Command Line: %s\n", (const char *)origCommandLine.ToUTF8());
	fprintf(diagFile, "Working Directory:%s\n", tQSL_BaseDir);
}

static void
AddEditStationLocation(tQSL_Location loc, bool expired = false, const wxString& title = wxT("Add Station Location"), const wxString& callsign = wxT("")) {
	tqslTrace("AddEditStationLocation", "loc=%lx, expired=%lx, title=%s, callsign=%s", loc, expired, S(title), S(callsign));
	try {
		run_station_wizard(frame, loc, frame->help, expired, title, wxT(""), callsign);
		frame->loc_tree->Build();
	}
	catch(TQSLException& x) {
		wxLogError(wxT("%hs"), x.what());
	}
}

void
MyFrame::AddStationLocation(wxCommandEvent& WXUNUSED(event)) {
	tqslTrace("MyFrame::AddStationLocation");
	wxTreeItemId root = loc_tree->GetRootItem();
	wxTreeItemId id = loc_tree->GetSelection();
	wxString call;
	if (id != root && id.IsOk()) {		// If something selected
		LocTreeItemData *data = reinterpret_cast<LocTreeItemData *>(loc_tree->GetItemData(id));
		if (data) {
			call = data->getCallSign();		// Station location
		} else {
			call = loc_tree->GetItemText(id);	// Callsign folder selected
		}
		tqslTrace("MyFrame::AddStationLocation", "Call selected is %s", S(call));
	}
	tQSL_Location loc;
	if (tqsl_initStationLocationCapture(&loc)) {
		wxLogError(wxT("%hs"), tqsl_getErrorString());
	}
	AddEditStationLocation(loc, false, wxT("Add Station Location"), call);
	if (tqsl_endStationLocationCapture(&loc)) {
		wxLogError(wxT("%hs"), tqsl_getErrorString());
	}
	loc_tree->Build();
	LocTreeReset();
}

void
MyFrame::EditStationLocation(wxCommandEvent& event) {
	tqslTrace("MyFrame::EditStationLocation");
	if (event.GetId() == tl_EditLoc) {
		LocTreeItemData *data = reinterpret_cast<LocTreeItemData *>(loc_tree->GetItemData(loc_tree->GetSelection()));
		tQSL_Location loc;
		wxString selname;
		char errbuf[512];

		if (data == NULL) return;

		check_tqsl_error(tqsl_getStationLocation(&loc, data->getLocname().ToUTF8()));
		if (!verify_cert(loc, true))	// Check if there is a certificate before editing
			return;
		check_tqsl_error(tqsl_getStationLocationErrors(loc, errbuf, sizeof(errbuf)));
		if (strlen(errbuf) > 0) {
			wxMessageBox(wxString::Format(wxT("%hs\nThe invalid data was ignored."), errbuf), wxT("Location data error"), wxOK|wxICON_EXCLAMATION, this);
		}
		char loccall[512];
		check_tqsl_error(tqsl_getLocationCallSign(loc, loccall, sizeof loccall));
		selname = run_station_wizard(this, loc, help, true, wxString::Format(wxT("Edit Station Location : %hs - %s"), loccall, data->getLocname().c_str()), data->getLocname());
		check_tqsl_error(tqsl_endStationLocationCapture(&loc));
		loc_tree->Build();
		LocTreeReset();
		return;
	}
	try {
		SelectStationLocation(wxT("Edit Station Location"), wxT("Close"), true);
		loc_tree->Build();
		LocTreeReset();
	}
	catch(TQSLException& x) {
		wxLogError(wxT("%hs"), x.what());
	}
}

void
MyFrame::WriteQSOFile(QSORecordList& recs, const char *fname, bool force) {
	tqslTrace("MyFrame::writeQSOFile", "fname=%s, force=%d", fname, force);
	if (recs.empty()) {
		wxLogWarning(wxT("No QSO records"));
		return;
	}
	wxString s_fname;
	if (fname)
		s_fname = wxString::FromUTF8(fname);
	if (s_fname == wxT("") || !force) {
		wxString path, basename, type;
		wxSplitPath(s_fname, &path, &basename, &type);
		if (type != wxT(""))
			basename += wxT(".") + type;
		if (path == wxT(""))
			path = wxConfig::Get()->Read(wxT("QSODataPath"), wxT(""));
		s_fname = wxFileSelector(wxT("Save File"), path, basename, wxT("adi"),
#if !defined(__APPLE__) && !defined(_WIN32)
			wxT("ADIF files (*.adi;*.adif;*.ADI;*.ADIF)|*.adi;*.adif;*.ADI;*.ADIF|All files (*.*)|*.*"),
#else
			wxT("ADIF files (*.adi;*.adif)|*.adi;*.adif|All files (*.*)|*.*"),
#endif
			wxFD_SAVE|wxFD_OVERWRITE_PROMPT, this);
		if (s_fname == wxT(""))
			return;
		wxConfig::Get()->Write(wxT("QSODataPath"), wxPathOnly(s_fname));
	}
	ofstream out(s_fname.ToUTF8(), ios::out|ios::trunc|ios::binary);
	if (!out.is_open())
		return;
	unsigned char buf[256];
	QSORecordList::iterator it;
	for (it = recs.begin(); it != recs.end(); it++) {
		wxString dtstr;
		tqsl_adifMakeField("CALL", 0, (const unsigned char*)(const char *)it->_call.ToUTF8(), -1, buf, sizeof buf);
		out << buf << endl;
		tqsl_adifMakeField("BAND", 0, (const unsigned char*)(const char *)it->_band.ToUTF8(), -1, buf, sizeof buf);
		out << "   " << buf << endl;
		tqsl_adifMakeField("MODE", 0, (const unsigned char*)(const char *)it->_mode.ToUTF8(), -1, buf, sizeof buf);
		out << "   " << buf << endl;
		dtstr.Printf(wxT("%04d%02d%02d"), it->_date.year, it->_date.month, it->_date.day);
		tqsl_adifMakeField("QSO_DATE", 0, (const unsigned char*)(const char *)dtstr.ToUTF8(), -1, buf, sizeof buf);
		out << "   " << buf << endl;
		dtstr.Printf(wxT("%02d%02d%02d"), it->_time.hour, it->_time.minute, it->_time.second);
		tqsl_adifMakeField("TIME_ON", 0, (const unsigned char*)(const char *)dtstr.ToUTF8(), -1, buf, sizeof buf);
		out << "   " << buf << endl;
		if (it->_freq != wxT("")) {
			tqsl_adifMakeField("FREQ", 0, (const unsigned char*)(const char *)it->_freq.ToUTF8(), -1, buf, sizeof buf);
			out << "   " << buf << endl;
		}
		if (it->_rxband != wxT("")) {
			tqsl_adifMakeField("BAND_RX", 0, (const unsigned char*)(const char *)it->_rxband.ToUTF8(), -1, buf, sizeof buf);
			out << "   " << buf << endl;
		}
		if (it->_rxfreq != wxT("")) {
			tqsl_adifMakeField("FREQ_RX", 0, (const unsigned char*)(const char *)it->_rxfreq.ToUTF8(), -1, buf, sizeof buf);
			out << "   " << buf << endl;
		}
		if (it->_propmode != wxT("")) {
			tqsl_adifMakeField("PROP_MODE", 0, (const unsigned char*)(const char *)it->_propmode.ToUTF8(), -1, buf, sizeof buf);
			out << "   " << buf << endl;
		}
		if (it->_satellite != wxT("")) {
			tqsl_adifMakeField("SAT_NAME", 0, (const unsigned char*)(const char *)it->_satellite.ToUTF8(), -1, buf, sizeof buf);
			out << "   " << buf << endl;
		}
		out << "<EOR>" << endl;
	}
	out.close();
	wxLogMessage(wxT("Wrote %d QSO records to %s"), static_cast<int>(recs.size()), s_fname.c_str());
}

static tqsl_adifFieldDefinitions fielddefs[] = {
        { "CALL", "", TQSL_ADIF_RANGE_TYPE_NONE, TQSL_CALLSIGN_MAX, 0, 0, 0, 0 },
        { "BAND", "", TQSL_ADIF_RANGE_TYPE_NONE, TQSL_BAND_MAX, 0, 0, 0, 0 },
        { "BAND_RX", "", TQSL_ADIF_RANGE_TYPE_NONE, TQSL_BAND_MAX, 0, 0, 0, 0 },
        { "MODE", "", TQSL_ADIF_RANGE_TYPE_NONE, TQSL_MODE_MAX, 0, 0, 0, 0 },
        { "FREQ", "", TQSL_ADIF_RANGE_TYPE_NONE, TQSL_FREQ_MAX, 0, 0, 0, 0 },
        { "FREQ_RX", "", TQSL_ADIF_RANGE_TYPE_NONE, TQSL_FREQ_MAX, 0, 0, 0, 0 },
        { "QSO_DATE", "", TQSL_ADIF_RANGE_TYPE_NONE, 8, 0, 0, 0, 0 },
        { "TIME_ON", "", TQSL_ADIF_RANGE_TYPE_NONE, 6, 0, 0, 0, 0 },
        { "SAT_NAME", "", TQSL_ADIF_RANGE_TYPE_NONE, TQSL_SATNAME_MAX, 0, 0, 0, 0 },
        { "PROP_MODE", "", TQSL_ADIF_RANGE_TYPE_NONE, TQSL_PROPMODE_MAX, 0, 0, 0, 0 },
        { "EOR", "", TQSL_ADIF_RANGE_TYPE_NONE, 0, 0, 0, 0, 0 },
        { "", "", TQSL_ADIF_RANGE_TYPE_NONE, 0, 0, 0, 0, 0 },
};

static const char *defined_types[] = { "T", "D", "M", "C", "N", "6" };

static unsigned char *
adif_alloc(size_t n) {
	return new unsigned char[n];
}

void
MyFrame::EditQSOData(wxCommandEvent& WXUNUSED(event)) {
	tqslTrace("MyFrame::EditQSOData");
	QSORecordList recs;
	wxString file = wxFileSelector(wxT("Open File"), wxConfig::Get()->Read(wxT("QSODataPath"), wxT("")), wxT(""), wxT("adi"),
#if !defined(__APPLE__) && !defined(_WIN32)
			wxT("ADIF files (*.adi;*.adif;*.ADI;*.ADIF)|*.adi;*.adif;*.ADI;*.ADIF|All files (*.*)|*.*"),
#else
			wxT("ADIF files (*.adi;*.adif)|*.adi;*.adif|All files (*.*)|*.*"),
#endif
			wxFD_OPEN|wxFD_FILE_MUST_EXIST, this);
	if (file == wxT(""))
		return;
	init_modes();
	tqsl_adifFieldResults field;
	TQSL_ADIF_GET_FIELD_ERROR stat;
	tQSL_ADIF adif;
	if (tqsl_beginADIF(&adif, file.ToUTF8())) {
		wxLogError(wxT("%hs"), tqsl_getErrorString());
	}
	QSORecord rec;
	do {
		if (tqsl_getADIFField(adif, &field, &stat, fielddefs, defined_types, adif_alloc)) {
			wxLogError(wxT("%hs"), tqsl_getErrorString());
		}
		if (stat == TQSL_ADIF_GET_FIELD_SUCCESS) {
			if (!strcasecmp(field.name, "CALL")) {
				rec._call = wxString::FromUTF8((const char *)field.data);
			} else if (!strcasecmp(field.name, "BAND")) {
				rec._band = wxString::FromUTF8((const char *)field.data);
			} else if (!strcasecmp(field.name, "BAND_RX")) {
				rec._rxband = wxString::FromUTF8((const char *)field.data);
			} else if (!strcasecmp(field.name, "MODE")) {
				rec._mode = wxString::FromUTF8((const char *)field.data);
				char amode[40];
				if (tqsl_getADIFMode(rec._mode.ToUTF8(), amode, sizeof amode) == 0 && amode[0] != '\0')
					rec._mode = wxString::FromUTF8(amode);
			} else if (!strcasecmp(field.name, "FREQ")) {
				rec._freq = wxString::FromUTF8((const char *)field.data);
			} else if (!strcasecmp(field.name, "FREQ_RX")) {
				rec._rxfreq = wxString::FromUTF8((const char *)field.data);
			} else if (!strcasecmp(field.name, "PROP_MODE")) {
				rec._propmode = wxString::FromUTF8((const char *)field.data);
			} else if (!strcasecmp(field.name, "SAT_NAME")) {
				rec._satellite = wxString::FromUTF8((const char *)field.data);
			} else if (!strcasecmp(field.name, "QSO_DATE")) {
				char *cp = reinterpret_cast<char *>(field.data);
				if (strlen(cp) == 8) {
					rec._date.day = strtol(cp+6, NULL, 10);
					*(cp+6) = '\0';
					rec._date.month = strtol(cp+4, NULL, 10);
					*(cp+4) = '\0';
					rec._date.year = strtol(cp, NULL, 10);
				}
			} else if (!strcasecmp(field.name, "TIME_ON")) {
				char *cp = reinterpret_cast<char *>(field.data);
				if (strlen(cp) >= 4) {
					rec._time.second = (strlen(cp) > 4) ? strtol(cp+4, NULL, 10) : 0;
					*(cp+4) = 0;
					rec._time.minute = strtol(cp+2, NULL, 10);
					*(cp+2) = '\0';
					rec._time.hour = strtol(cp, NULL, 10);
				}
			} else if (!strcasecmp(field.name, "EOR")) {
				recs.push_back(rec);
				rec = QSORecord();
			}
			delete[] field.data;
		}
	} while (stat == TQSL_ADIF_GET_FIELD_SUCCESS || stat == TQSL_ADIF_GET_FIELD_NO_NAME_MATCH);
	tqsl_endADIF(&adif);
	try {
		QSODataDialog dial(this, help, &recs);
		if (dial.ShowModal() == wxID_OK)
			WriteQSOFile(recs, file.ToUTF8());
	} catch(TQSLException& x) {
		wxLogError(wxT("%hs"), x.what());
	}
}

void
MyFrame::EnterQSOData(wxCommandEvent& WXUNUSED(event)) {
	tqslTrace("MyFrame::EnterQSOData");
	QSORecordList recs;
	try {
		QSODataDialog dial(this, help, &recs);
		if (dial.ShowModal() == wxID_OK)
			WriteQSOFile(recs);
	} catch(TQSLException& x) {
		wxLogError(wxT("%hs"), x.what());
	}
}

int MyFrame::ConvertLogToString(tQSL_Location loc, const wxString& infile, wxString& output, int& n, tQSL_Converter& conv, bool suppressdate, tQSL_Date* startdate, tQSL_Date* enddate, int action, const char* password) {
	tqslTrace("MyFrame::ConvertLogToString", "loc = %lx, infile=%s, output=%s n=%d conv=%lx, suppressdate=%d, startdate=0x%lx, enddate=0x%lx, action=%d", reinterpret_cast<void *>(loc), S(infile), S(output), reinterpret_cast<void *>(conv), suppressdate, reinterpret_cast<void *>(startdate), reinterpret_cast<void *>(enddate), action);
	static const char *iam = "TQSL V" VERSION;
	const char *cp;
	char callsign[40];
	int dxcc = 0;
	wxString name, ext;
	bool allow_dupes = false;
	bool restarting = false;
	bool ignore_err = false;

	wxConfig *config = reinterpret_cast<wxConfig *>(wxConfig::Get());

	check_tqsl_error(tqsl_getLocationCallSign(loc, callsign, sizeof callsign));
	tqsl_getLocationDXCCEntity(loc, &dxcc);
	DXCC dx;
	dx.getByEntity(dxcc);

	get_certlist(callsign, dxcc, false, false, false);
	if (ncerts == 0) {
		wxString msg;
		if (dxcc != 0)
			msg = wxString::Format(wxT("There are no valid callsign certificates for callsign %hs in entity %hs.\nSigning aborted.\n"), callsign, dx.name());
		else
			msg = wxString::Format(wxT("There are no valid callsign certificates for callsign %hs.\nSigning aborted.\n"), callsign);
		throw TQSLException(msg.ToUTF8());
		return TQSL_EXIT_TQSL_ERROR;
	}

	wxLogMessage(wxT("Signing using Callsign %hs, DXCC Entity %hs\n"), callsign, dx.name());

	init_modes();
	init_contests();

	if (lock_db(false) < 0) {
		wxSafeYield();
		wxLogMessage(wxT("TQSL must wait for other running copies of TQSL to exit before signing..."));
		wxSafeYield();
		lock_db(true);
	}

 restart:

	ConvertingDialog *conv_dial = new ConvertingDialog(this, infile.ToUTF8());
	n = 0;
	bool cancelled = false;
	bool aborted = false;
	int lineno = 0;
	int out_of_range = 0;
	int duplicates = 0;
	int processed = 0;
	int errors = 0;
	try {
		if (tqsl_beginCabrilloConverter(&conv, tqslName(infile), certlist, ncerts, loc)) {
			if (tQSL_Error != TQSL_CABRILLO_ERROR || tQSL_Cabrillo_Error != TQSL_CABRILLO_NO_START_RECORD)
				check_tqsl_error(1);	// A bad error
			lineno = 0;
	   		check_tqsl_error(tqsl_beginADIFConverter(&conv, tqslName(infile), certlist, ncerts, loc));
		}
		bool range = true;
		config->Read(wxT("DateRange"), &range);
		if (range && !suppressdate && !restarting) {
			DateRangeDialog dial(this);
			if (dial.ShowModal() != wxOK) {
				wxLogMessage(wxT("Cancelled"));
				unlock_db();
				return TQSL_EXIT_CANCEL;
			}
			tqsl_setADIFConverterDateFilter(conv, &dial.start, &dial.end);
			if (this->IsQuiet()) {
				this->Show(false);
				wxSafeYield(this);
			}
		}
		if (startdate || enddate) {
			tqslTrace("MyFrame::ConvertLogToString", "startdate %d/%d/%d, enddate %d/%d/%d",
					startdate ? startdate->year : 0,
					startdate ? startdate->month : 0,
					startdate ? startdate->day : 0,
					enddate ? enddate->year : 0,
					enddate ? enddate->month : 0,
					enddate ? enddate->day : 0);
			tqsl_setADIFConverterDateFilter(conv, startdate, enddate);
		}
		bool allow = false;
		config->Read(wxT("BadCalls"), &allow);
		tqsl_setConverterAllowBadCall(conv, allow);
		tqsl_setConverterAllowDuplicates(conv, allow_dupes);
		tqsl_setConverterAppName(conv, iam);

		wxSplitPath(infile, 0, &name, &ext);
		if (ext != wxT(""))
			name += wxT(".") + ext;
		// Only display windows if notin batch mode -- KD6PAG
		if (!this->IsQuiet()) {
			conv_dial->Show(TRUE);
		}
		this->Enable(FALSE);

		output = wxT("");

		do {
	   		while ((cp = tqsl_getConverterGABBI(conv)) != 0) {
				if (!this->IsQuiet())
					wxSafeYield(conv_dial);
				if (!conv_dial->running)
					break;
				// Only count QSO records
				if (strstr(cp, "tCONTACT")) {
					++n;
					++processed;
				}
				if ((processed % 10) == 0) {
					wxString progress = wxString::Format(wxT("QSOs: %d"), processed);
					if (duplicates > 0)
						progress += wxString::Format(wxT(" Duplicates: %d"), duplicates);
					if (errors > 0 || out_of_range > 0)
						progress += wxString::Format(wxT(" Errors: %d"), errors + out_of_range);
		   	   		conv_dial->msg->SetLabel(progress);
				}
				output << (wxString::FromUTF8(cp) + wxT("\n"));
			}
			if ((processed % 10) == 0) {
				wxString progress = wxString::Format(wxT("QSOs: %d"), processed);
				if (duplicates > 0)
					progress += wxString::Format(wxT(" Duplicates: %d"), duplicates);
				if (errors > 0 || out_of_range > 0)
					progress += wxString::Format(wxT(" Errors: %d"), errors + out_of_range);
				conv_dial->msg->SetLabel(progress);
			}
			if (cp == 0) {
				if (!this->IsQuiet())
					wxSafeYield(conv_dial);
				if (!conv_dial->running)
					break;
			}
			if (tQSL_Error == TQSL_SIGNINIT_ERROR) {
				tQSL_Cert cert;
				int rval;
				check_tqsl_error(tqsl_getConverterCert(conv, &cert));
				do {
	   				if ((rval = tqsl_beginSigning(cert, const_cast<char *>(password), getCertPassword, cert)) == 0)
						break;
					if (tQSL_Error == TQSL_PASSWORD_ERROR) {
						if ((rval = tqsl_beginSigning(cert, const_cast<char *>(unipwd), NULL, cert)) == 0)
							break;
					}
					if (tQSL_Error == TQSL_PASSWORD_ERROR) {
						wxLogMessage(wxT("Password error"));
						if (password)
							free(reinterpret_cast<void *>(const_cast<char *>(password)));
						password = NULL;
					}
				} while (tQSL_Error == TQSL_PASSWORD_ERROR);
				check_tqsl_error(rval);
				if (this->IsQuiet()) {
					this->Show(false);
					wxSafeYield(this);
				}
				continue;
			}
			if (tQSL_Error == TQSL_DATE_OUT_OF_RANGE) {
				processed++;
				out_of_range++;
				continue;
			}
			if (tQSL_Error == TQSL_DUPLICATE_QSO) {
				processed++;
				duplicates++;
				continue;
			}
			bool has_error = (tQSL_Error != TQSL_NO_ERROR);
			if (has_error) {
				processed++;
				errors++;
				try {
					check_tqsl_error(1);
				} catch(TQSLException& x) {
					tqsl_getConverterLine(conv, &lineno);
					wxString msg = wxString::FromUTF8(x.what());
					if (lineno)
						msg += wxString::Format(wxT(" on line %d"), lineno);
					const char *bad_text = tqsl_getConverterRecordText(conv);
					if (bad_text)
						msg += wxString(wxT("\n")) + wxString::FromUTF8(bad_text);

					wxLogError(wxT("%s"), msg.c_str());
					if (frame->IsQuiet()) {
						switch (action) {
                                                        case TQSL_ACTION_ABORT:
								aborted = true;
								ignore_err = true;
								goto abortSigning;
                                                        case TQSL_ACTION_NEW:		// For ALL or NEW, let the signing proceed
                                                        case TQSL_ACTION_ALL:
								ignore_err = true;
								break;
                                                        case TQSL_ACTION_ASK:
                                                        case TQSL_ACTION_UNSPEC:
								break;			// The error will show as a popup
						}
					}
					if (!ignore_err) {
						tqslTrace("MyFrame::ConvertLogToString", "Error: %s/asking for action", S(msg));
						ErrorsDialog dial(this, msg + wxT("\nClick 'Ignore' to continue signing this log while ignoring errors.\n")
								wxT("Click 'Cancel' to abandon signing this log."));
						int choice = dial.ShowModal();
						if (choice == TQSL_AE_CAN) {
							cancelled = true;
							goto abortSigning;
						}
						if (choice == TQSL_AE_OK) {
							ignore_err = true;
							if (this->IsQuiet()) {
								this->Show(false);
								wxSafeYield(this);
							}
						}
					}
				}
			}
			tqsl_getErrorString();	// Clear error
			if (has_error && ignore_err)
				continue;
			break;
		} while (1);
		cancelled = !conv_dial->running;

 abortSigning:
		this->Enable(TRUE);

		if (cancelled) {
			wxLogWarning(wxT("Signing cancelled"));
			n = 0;
		} else if (aborted) {
			wxLogWarning(wxT("Signing aborted"));
			n = 0;
		} else if (tQSL_Error != TQSL_NO_ERROR) {
			check_tqsl_error(1);
		}
		delete conv_dial;
	} catch(TQSLException& x) {
		this->Enable(TRUE);
		delete conv_dial;
		string msg = x.what();
		tqsl_getConverterLine(conv, &lineno);
		tqsl_converterRollBack(conv);
		tqsl_endConverter(&conv);
		unlock_db();
		if (lineno)
			msg += wxString::Format(wxT(" on line %d"), lineno).ToUTF8();

		wxLogError(wxT("Signing aborted due to errors"));
		throw TQSLException(msg.c_str());
	}
	if (!cancelled && out_of_range > 0)
		wxLogMessage(wxT("%s: %d QSO records were outside the selected date range"),
			infile.c_str(), out_of_range);
	if (duplicates > 0) {
		if (cancelled) {
			tqsl_converterRollBack(conv);
			tqsl_endConverter(&conv);
			unlock_db();
			return TQSL_EXIT_CANCEL;
		}
		if (action == TQSL_ACTION_ASK || action == TQSL_ACTION_UNSPEC) { // want to ask the user
			DupesDialog dial(this, processed - errors - out_of_range, duplicates, action);
			int choice = dial.ShowModal();
			if (choice == TQSL_DP_CAN) {
				wxLogMessage(wxT("Cancelled"));
				tqsl_converterRollBack(conv);
				tqsl_endConverter(&conv);
				unlock_db();
				return TQSL_EXIT_CANCEL;
			}
			if (choice == TQSL_DP_ALLOW) {
				allow_dupes = true;
				tqsl_converterRollBack(conv);
				tqsl_endConverter(&conv);
				restarting = true;
				if (this->IsQuiet()) {
					this->Show(false);
					wxSafeYield(this);
				}
				goto restart;
			}
		} else if (action == TQSL_ACTION_ABORT) {
				if (processed == duplicates) {
					wxLogMessage(wxT("All QSOs are duplicates; aborted"));
					tqsl_converterRollBack(conv);
					tqsl_endConverter(&conv);
					unlock_db();
					n = 0;
					return TQSL_EXIT_NO_QSOS;
				} else {
					wxLogMessage(wxT("%d of %d QSOs are duplicates; aborted"), duplicates, processed);
					tqsl_converterRollBack(conv);
					tqsl_endConverter(&conv);
					unlock_db();
					n = 0;
					return TQSL_EXIT_NO_QSOS;
				}
		} else if (action == TQSL_ACTION_ALL) {
			allow_dupes = true;
			tqsl_converterRollBack(conv);
			tqsl_endConverter(&conv);
			restarting = true;
			goto restart;
		}
		// Otherwise it must be TQSL_ACTION_NEW, so fall through
		// and output the new records.
		wxLogMessage(wxT("%s: %d QSO records were duplicates"),
			infile.c_str(), duplicates);
	}
	//if (!cancelled) tqsl_converterCommit(conv);
	if (cancelled || processed == 0) {
		tqsl_converterRollBack(conv);
		tqsl_endConverter(&conv);
	}
	unlock_db();
	if (cancelled)
		return TQSL_EXIT_CANCEL;
	if (processed == 0)
		return TQSL_EXIT_NO_QSOS;
	if (aborted || duplicates > 0 || out_of_range > 0 || errors > 0)
		return TQSL_EXIT_QSOS_SUPPRESSED;
	return TQSL_EXIT_SUCCESS;
}

int
MyFrame::ConvertLogFile(tQSL_Location loc, const wxString& infile, const wxString& outfile,
	bool compressed, bool suppressdate, tQSL_Date* startdate, tQSL_Date* enddate, int action, const char *password) {
	tqslTrace("MyFrame::ConvertLogFile", "loc=%lx, infile=%s, outfile=%s, compressed=%d, suppressdate=%d, startdate=0x%lx enddate=0x%lx action=%d", reinterpret_cast<void *>(loc), S(infile), S(outfile), compressed, suppressdate, reinterpret_cast<void *>(startdate), reinterpret_cast<void*>(enddate), action);

	gzFile gout = 0;
	ofstream out;

	if (compressed)
		gout = gzopen(tqslName(outfile), "wb9");
	else
		out.open(tqslName(outfile), ios::out|ios::trunc|ios::binary);

	if ((compressed && !gout) || (!compressed && !out)) {
		wxLogError(wxT("Unable to open %s for output"), outfile.c_str());
		return TQSL_EXIT_ERR_OPEN_OUTPUT;
	}

	wxString output;
	int numrecs = 0;
	tQSL_Converter conv = 0;
	int status = this->ConvertLogToString(loc, infile, output, numrecs, conv, suppressdate, startdate, enddate, action, password);

	if (numrecs == 0) {
		wxLogMessage(wxT("No records output"));
		if (compressed) {
			gzclose(gout);
		} else {
			out.close();
		}
		unlink(tqslName(outfile));
		if (status == TQSL_EXIT_CANCEL || TQSL_EXIT_QSOS_SUPPRESSED)
			return status;
		else
			return TQSL_EXIT_NO_QSOS;
	} else {
		if(compressed) {
			if (0 >= gzwrite(gout, tqslName(output), output.size()) || Z_OK != gzclose(gout)) {
				tqsl_converterRollBack(conv);
				tqsl_endConverter(&conv);
				return TQSL_EXIT_LIB_ERROR;
			}
		} else {
			out << output;
			if (out.fail()) {
				tqsl_converterRollBack(conv);
				tqsl_endConverter(&conv);
				return TQSL_EXIT_LIB_ERROR;
			}
			out.close();
			if (out.fail()) {
				tqsl_converterRollBack(conv);
				tqsl_endConverter(&conv);
				return TQSL_EXIT_LIB_ERROR;
			}
		}

		tqsl_converterCommit(conv);
		tqsl_endConverter(&conv);

		wxLogMessage(wxT("%s: wrote %d records to %s"), infile.c_str(), numrecs,
			outfile.c_str());
		wxLogMessage(wxT("%s is ready to be emailed or uploaded.\nNote: TQSL assumes that this file will be uploaded to LoTW.\nResubmitting these QSOs will cause them to be reported as duplicates."), outfile.c_str());
	}

	return status;
}

class FileUploadHandler {
 public:
	string s;
	FileUploadHandler(): s() { s.reserve(2000); }

	size_t internal_recv(char *ptr, size_t size, size_t nmemb) {
		s.append(ptr, size*nmemb);
		return size*nmemb;
	}

	static size_t recv(char *ptr, size_t size, size_t nmemb, void *userdata) {
		return (reinterpret_cast<FileUploadHandler*>(userdata))->internal_recv(ptr, size, nmemb);
	}
};

class ConfigFileDownloadHandler {
 public:
	void *s;
	size_t allocated;
	size_t used;
	explicit ConfigFileDownloadHandler(size_t _size): s() {
		allocated = _size;
		s = malloc(_size);
		used = 0;
	}
	~ConfigFileDownloadHandler(void);
	size_t internal_recv(char *ptr, size_t size, size_t nmemb) {
		size_t newlen = used + (size * nmemb);
		if (newlen > allocated) {
			s = realloc(s, newlen + 2000);
			allocated += newlen + 2000;
		}
		memcpy(reinterpret_cast<char *>(s)+used, ptr, size * nmemb);
		used += size*nmemb;
		return size*nmemb;
	}

	static size_t recv(char *ptr, size_t size, size_t nmemb, void *userdata) {
		return (reinterpret_cast<ConfigFileDownloadHandler*>(userdata))->internal_recv(ptr, size, nmemb);
	}
};

ConfigFileDownloadHandler::~ConfigFileDownloadHandler(void) {
	if (s) free(s);
}

long compressToBuf(string& buf, const char* input) {
	tqslTrace("compressToBuf");
	const size_t TBUFSIZ = 128*1024;
	uint8_t* tbuf = new uint8_t[TBUFSIZ];

	//vector<uint8_t> buf;
	z_stream stream;
	stream.zalloc = 0;
	stream.zfree = 0;
	stream.next_in = reinterpret_cast<Bytef*>(const_cast<char *>(input));
	stream.avail_in = strlen(input);
	stream.next_out = tbuf;
	stream.avail_out = TBUFSIZ;

	//deflateInit(&stream, Z_BEST_COMPRESSION);
	deflateInit2(&stream, Z_BEST_COMPRESSION, Z_DEFLATED, 16+15, 9, Z_DEFAULT_STRATEGY); //use gzip header

	while (stream.avail_in) { //while still some left
		int res = deflate(&stream, Z_NO_FLUSH);
		assert(res == Z_OK);
		if (!stream.avail_out) {
			buf.insert(buf.end(), tbuf, tbuf+TBUFSIZ);
			stream.next_out = tbuf;
			stream.avail_out = TBUFSIZ;
		}
	}

	do {
		if (stream.avail_out == 0) {
			buf.insert(buf.end(), tbuf, tbuf+TBUFSIZ);
			stream.next_out = tbuf;
			stream.avail_out = TBUFSIZ;
		}
	} while (deflate(&stream, Z_FINISH) == Z_OK);

	buf.insert(buf.end(), tbuf, tbuf+TBUFSIZ-stream.avail_out);
	deflateEnd(&stream);

	delete tbuf;

	return buf.length();
}


class UploadThread: public wxThread {
 public:
  UploadThread(CURL* handle_, wxDialog* dial_): wxThread(wxTHREAD_JOINABLE),
						handle(handle_), dial(dial_) {
		wxThread::Create();
	}
 protected:
	CURL* handle;
	wxDialog* dial;
	virtual wxThread::ExitCode Entry() {
		int ret = curl_easy_perform(handle);
		wxCommandEvent evt(wxEVT_LOGUPLOAD_DONE, wxID_ANY);
		dial->GetEventHandler()->AddPendingEvent(evt);
		return (wxThread::ExitCode)((intptr_t)ret);
	}
};

int MyFrame::UploadLogFile(tQSL_Location loc, const wxString& infile, bool compressed, bool suppressdate, tQSL_Date* startdate, tQSL_Date* enddate, int action, const char* password) {
	tqslTrace("MyFrame::UploadLogFile", "loc=%lx, infile=%s, compressed=%d, suppressdate=%d, startdate=0x%lx, enddate=0x%lx action=%d", reinterpret_cast<void *>(loc), S(infile), compressed, suppressdate, reinterpret_cast<void *>(startdate), reinterpret_cast<void *>(enddate), action);
	int numrecs = 0;
	wxString signedOutput;
	tQSL_Converter conv = 0;

	int status = this->ConvertLogToString(loc, infile, signedOutput, numrecs, conv, suppressdate, startdate, enddate, action, password);

	if (numrecs == 0) {
		wxLogMessage(wxT("No records to upload"));
		if (status == TQSL_EXIT_CANCEL || TQSL_EXIT_QSOS_SUPPRESSED)
			return status;
		else
			return TQSL_EXIT_NO_QSOS;
	} else {
		//compress the upload
		string compressed;
		size_t compressedSize = compressToBuf(compressed, (const char*)signedOutput.ToUTF8());
		//ofstream f; f.open("testzip.tq8", ios::binary); f<<compressed; f.close(); //test of compression routine
		if (compressedSize < 0) {
			wxLogMessage(wxT("Error compressing before upload"));
			return TQSL_EXIT_TQSL_ERROR;
		}

		wxDateTime now = wxDateTime::Now().ToUTC();

		wxString name, ext;
		wxFileName::SplitPath(infile, 0, &name, &ext);
		name += wxT(".tq8");

		//unicode mess. can't just use mb_str directly because it's a temp ptr
		// and the curl form expects it to still be there during perform() so
		// we have to do all this copying around to please the unicode gods

		char filename[1024];
		strncpy(filename, wxString::Format(wxT("<TQSLUpl %s-%s> %s"),
			now.Format(wxT("%Y%m%d")).c_str(),
			now.Format(wxT("%H%M")).c_str(),
			name.c_str()).ToUTF8(), sizeof filename);
		filename[sizeof filename - 1] = '\0';

		wxString fileType(wxT("Log"));
		int retval = UploadFile(infile, filename, numrecs, reinterpret_cast<void *>(const_cast<char *>(compressed.c_str())),
					compressedSize, fileType);

		if (retval == 0)
			tqsl_converterCommit(conv);
		else
			tqsl_converterRollBack(conv);

		tqsl_endConverter(&conv);

		return retval;
	}
}

static CURL*
tqsl_curl_init(const char *logTitle, const char *url, FILE **curlLogFile, bool newFile) {
	CURL* curlReq = curl_easy_init();
	if (!curlReq)
		return NULL;

	if (diagFile) {
		curl_easy_setopt(curlReq, CURLOPT_VERBOSE, 1);
		curl_easy_setopt(curlReq, CURLOPT_STDERR, diagFile);
		fprintf(diagFile, "%s\n", logTitle);
	} else {
		wxString filename;
#ifdef _WIN32
		filename.Printf(wxT("%hs\\curl.log"), tQSL_BaseDir);
#else
		filename.Printf(wxT("%hs/curl.log"), tQSL_BaseDir);
#endif
		*curlLogFile = fopen(tqslName(filename), newFile ? "wb" : "ab");
		if (*curlLogFile) {
			curl_easy_setopt(curlReq, CURLOPT_VERBOSE, 1);
			curl_easy_setopt(curlReq, CURLOPT_STDERR, *curlLogFile);
			fprintf(*curlLogFile, "%s:\n", logTitle);
		}
	}
	//set up options
	curl_easy_setopt(curlReq, CURLOPT_URL, url);

	DocPaths docpaths(wxT("tqslapp"));
	docpaths.Add(wxString::FromUTF8(tQSL_BaseDir));
#ifdef CONFDIR
	docpaths.Add(wxT(CONFDIR));
#endif
#ifdef _WIN32
	wxStandardPaths sp;
	wxString exePath;
	wxSplitPath(sp.GetExecutablePath(), &exePath, 0, 0);
	docpaths.Add(exePath);
#endif
	wxString caBundlePath = docpaths.FindAbsoluteValidPath(wxT("ca-bundle.crt"));
	if (!caBundlePath.IsEmpty()) {
		char caBundle[256];
		strncpy(caBundle, tqslName(caBundlePath), sizeof caBundle);
		curl_easy_setopt(curlReq, CURLOPT_CAINFO, caBundle);
	}
	// Get the proxy configuration and pass it to cURL
	wxConfig *config = reinterpret_cast<wxConfig *>(wxConfig::Get());
	config->SetPath(wxT("/Proxy"));

	bool enabled;
	config->Read(wxT("proxyEnabled"), &enabled, false);
	wxString pHost = config->Read(wxT("proxyHost"), wxT(""));
	wxString pPort = config->Read(wxT("proxyPort"), wxT(""));
	wxString pType = config->Read(wxT("proxyType"), wxT(""));
	config->SetPath(wxT("/"));

	if (!enabled) return curlReq;	// No proxy defined

	long port = strtol(pPort.ToUTF8(), NULL, 10);
	if (port == 0 || pHost.IsEmpty())
		return curlReq;		// Invalid proxy. Ignore it.

	curl_easy_setopt(curlReq, CURLOPT_PROXY, (const char *)pHost.ToUTF8());
	curl_easy_setopt(curlReq, CURLOPT_PROXYPORT, port);
	if (pType == wxT("HTTP")) {
		curl_easy_setopt(curlReq, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);	// Default is HTTP
	} else if (pType == wxT("Socks4")) {
		curl_easy_setopt(curlReq, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
	} else if (pType == wxT("Socks5")) {
		curl_easy_setopt(curlReq, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
	}
	return curlReq;
}

int MyFrame::UploadFile(const wxString& infile, const char* filename, int numrecs, void *content, size_t clen, const wxString& fileType) {
	tqslTrace("MyFrame::UploadFile", "infile=%s, filename=%s, numrecs=%d, content=0x%lx, clen=%d fileType=%s",  S(infile), filename, numrecs, reinterpret_cast<void *>(content), clen, S(fileType));

	//upload the file

	//get the url from the config, can be overridden by an installer
	//defaults are valid for LoTW as of 1/31/2013

	wxConfig *config = reinterpret_cast<wxConfig *>(wxConfig::Get());
	config->SetPath(wxT("/LogUpload"));
	wxString uploadURL = config->Read(wxT("UploadURL"), DEFAULT_UPL_URL);
	wxString uploadField = config->Read(wxT("PostField"), DEFAULT_UPL_FIELD);
	wxString uplStatus = config->Read(wxT("StatusRegex"), DEFAULT_UPL_STATUSRE);
	wxString uplStatusSuccess = config->Read(wxT("StatusSuccess"), DEFAULT_UPL_STATUSOK).Lower();
	wxString uplMessage = config->Read(wxT("MessageRegex"), DEFAULT_UPL_MESSAGERE);
	bool uplVerifyCA;
	config->Read(wxT("VerifyCA"), &uplVerifyCA, DEFAULT_UPL_VERIFYCA);
	config->SetPath(wxT("/"));

	// Copy the strings so they remain around
	char *urlstr = strdup(uploadURL.ToUTF8());
	char *cpUF = strdup(uploadField.ToUTF8());

 retry_upload:

	curlReq = tqsl_curl_init("Upload Log", urlstr, &curlLogFile, true);

	if (!curlReq) {
		wxLogMessage(wxT("Error: Could not upload file (CURL Init error)"));
		free(urlstr);
		free(cpUF);
		return TQSL_EXIT_TQSL_ERROR;
	}

	//the following allow us to write our log and read the result

	FileUploadHandler handler;

	curl_easy_setopt(curlReq, CURLOPT_WRITEFUNCTION, &FileUploadHandler::recv);
	curl_easy_setopt(curlReq, CURLOPT_WRITEDATA, &handler);
	curl_easy_setopt(curlReq, CURLOPT_SSL_VERIFYPEER, uplVerifyCA);

	char errorbuf[CURL_ERROR_SIZE];
	errorbuf[0] = '\0';
	curl_easy_setopt(curlReq, CURLOPT_ERRORBUFFER, errorbuf);

	struct curl_httppost* post = NULL, *lastitem = NULL;

	curl_formadd(&post, &lastitem,
		CURLFORM_PTRNAME, cpUF,
		CURLFORM_BUFFER, filename,
		CURLFORM_BUFFERPTR, content,
		CURLFORM_BUFFERLENGTH, clen,
		CURLFORM_END);

	curl_easy_setopt(curlReq, CURLOPT_HTTPPOST, post);

	intptr_t retval;

	UploadDialog* upload;

	if (numrecs > 0)
		wxLogMessage(wxT("Attempting to upload %d QSO%hs"), numrecs, numrecs == 1 ? "" : "s");
	else
		wxLogMessage(wxT("Attempting to upload %s"), fileType.c_str());

	if(this) {
		if (fileType == wxT("Log")) {
			upload = new UploadDialog(this);
		} else {
			upload = new UploadDialog(this, wxString(wxT("Uploading Callsign Certificate")), wxString(wxT("Uploading Callsign Certificate Request...")));
		}

		curl_easy_setopt(curlReq, CURLOPT_PROGRESSFUNCTION, &UploadDialog::UpdateProgress);
		curl_easy_setopt(curlReq, CURLOPT_PROGRESSDATA, upload);
		curl_easy_setopt(curlReq, CURLOPT_NOPROGRESS, 0);

		UploadThread thread(curlReq, upload);
		if (thread.Run() != wxTHREAD_NO_ERROR) {
			wxLogError(wxT("Could not spawn upload thread!"));
		        upload->Destroy();
			free(urlstr);
			free(cpUF);
			if (curlLogFile) {
				fclose(curlLogFile);
				curlLogFile = NULL;
			}
			return TQSL_EXIT_TQSL_ERROR;
		}

		upload->ShowModal();
		retval=((intptr_t)thread.Wait());
	} else { retval = curl_easy_perform(curlReq); }

	if (retval == 0) { //success
		//check the result

		wxString uplresult = wxString::FromAscii(handler.s.c_str());

		wxRegEx uplStatusRE(uplStatus);
		wxRegEx uplMessageRE(uplMessage);
		wxRegEx stripSpacesRE(wxT("\\n +"));

		if (uplStatusRE.Matches(uplresult)) { //we can make sense of the error
			//sometimes has leading/trailing spaces
			if (uplStatusRE.GetMatch(uplresult, 1).Lower().Trim(true).Trim(false) == uplStatusSuccess) { //success
				if (uplMessageRE.Matches(uplresult)) { //and a message
					wxString lotwmessage = uplMessageRE.GetMatch(uplresult, 1).Trim(true).Trim(false);
					stripSpacesRE.Replace(&lotwmessage, wxString(wxT("\\n")), 0);
					if (fileType == wxT("Log")) {
						wxLogMessage(wxT("%s: Log uploaded successfully with result \"%s\"!\nAfter reading this message, you may close this program."),
							infile.c_str(), lotwmessage.c_str());

					} else {
						wxLogMessage(wxT("%s uploaded with result \"%s\"!"),
							fileType.c_str(), lotwmessage.c_str());
					}
				} else { // no message we could find
					if (fileType == wxT("Log")) {
						wxLogMessage(wxT("%s: Log uploaded successfully!\nAfter reading this message, you may close this program."), infile.c_str());
					} else {
						wxLogMessage(wxT("%s uploaded successfully!"), fileType.c_str());
					}
				}

				retval = TQSL_EXIT_SUCCESS;
			} else { // failure, but site is working
				if (uplMessageRE.Matches(uplresult)) { //and a message
					wxLogMessage(wxT("%s: %s upload was rejected with result \"%s\""),
						infile.c_str(), fileType.c_str(), uplMessageRE.GetMatch(uplresult, 1).c_str());

				} else { // no message we could find
					wxLogMessage(wxT("%s: %s upload was rejected!"), infile.c_str(), fileType.c_str());
				}

				retval = TQSL_EXIT_REJECTED;
			}
		} else { //site isn't working
			wxLogMessage(wxT("%s: Got an unexpected response on %s upload! Maybe the site is down?"), infile.c_str(), fileType.c_str());
			retval = TQSL_EXIT_UNEXP_RESP;
		}

	} else {
		if (diagFile) {
			fprintf(diagFile, "cURL Error: %s (%s)\n", curl_easy_strerror((CURLcode)retval), errorbuf);
		}
		if (retval == CURLE_COULDNT_RESOLVE_HOST || retval == CURLE_COULDNT_CONNECT) {
			wxLogMessage(wxT("%s: Unable to upload - either your Internet connection is down or LoTW is unreachable.\nPlease try uploading the %s later."), infile.c_str(), fileType.c_str());
			retval = TQSL_EXIT_CONNECTION_FAILED;
		} else if (retval == CURLE_WRITE_ERROR || retval == CURLE_SEND_ERROR || retval == CURLE_RECV_ERROR) {
			wxLogMessage(wxT("%s: Unable to upload. The nework is down or the LoTW site is too busy.\nPlease try uploading the %s later."), infile.c_str(), fileType.c_str());
			retval = TQSL_EXIT_CONNECTION_FAILED;
		} else if (retval == CURLE_SSL_CONNECT_ERROR) {
			wxLogMessage(wxT("%s: Unable to connect to the upload site.\nPlease try uploading the %s later."), infile.c_str(), fileType.c_str());
			retval = TQSL_EXIT_CONNECTION_FAILED;
		} else if (retval == CURLE_ABORTED_BY_CALLBACK) { //cancelled.
			wxLogMessage(wxT("%s: Upload cancelled"), infile.c_str());
			retval = TQSL_EXIT_CANCEL;
		} else { //error
			//don't know why the conversion from char* -> wxString -> char* is necessary but it
			// was turned into garbage otherwise
			wxLogMessage(wxT("%s: Couldn't upload the file: CURL returned \"%hs\" (%hs)"), infile.c_str(), curl_easy_strerror((CURLcode)retval), errorbuf);
			retval = TQSL_EXIT_TQSL_ERROR;
		}
	}
	if (this) upload->Destroy();

	curl_formfree(post);
	curl_easy_cleanup(curlReq);

	// If there's a GUI and we didn't successfully upload and weren't cancelled,
	// ask the user if we should retry the upload.
	if (this && retval != TQSL_EXIT_CANCEL && retval != TQSL_EXIT_SUCCESS) {
		if (wxMessageBox(wxT("Your upload appears to have failed. Should TQSL try again?"), wxT("Retry?"), wxYES_NO, this) == wxYES)
			goto retry_upload;
	}

	if (urlstr) free(urlstr);
	if (cpUF) free (cpUF);
	if (curlLogFile) {
		fclose(curlLogFile);
		curlLogFile = NULL;
	}
	return retval;
}

// Verify that a certificate exists for this station location
// before allowing the location to be edited
static bool verify_cert(tQSL_Location loc, bool editing) {
	tqslTrace("verify_cert", "loc=%lx, editing=%d", reinterpret_cast<void *>(loc), editing);
	char call[128];
	tQSL_Cert *certlist;
	int ncerts;
	// Get the callsign from the location
	check_tqsl_error(tqsl_getLocationCallSign(loc, call, sizeof(call)));
	// See if there is a certificate for that call
	int flags = 0;
	if (editing)
		flags = TQSL_SELECT_CERT_WITHKEYS | TQSL_SELECT_CERT_EXPIRED;
	tqsl_selectCertificates(&certlist, &ncerts, call, 0, 0, 0, flags);
	if (ncerts == 0) {
		if (editing) {
			wxMessageBox(wxString::Format(wxT("There are no callsign certificates for callsign %hs. This station location cannot be edited."), call), wxT("No Certificate"), wxOK|wxICON_EXCLAMATION);
		} else {
			wxMessageBox(wxString::Format(wxT("There are no current callsign certificates for callsign %hs. This station location cannot be used to sign a log file."), call), wxT("No Certificate"), wxOK|wxICON_EXCLAMATION);
		}
		return false;
	}
	for (int i = 0; i  < ncerts; i++)
		tqsl_freeCertificate(certlist[i]);
	tqsl_freeStationDataEnc(reinterpret_cast<char *>(certlist));
	return true;
}

tQSL_Location
MyFrame::SelectStationLocation(const wxString& title, const wxString& okLabel, bool editonly) {
	tqslTrace("MyFrame::SelectStationLocation", "title=%s, okLabel=%s, editonly=%d", S(title), S(okLabel), editonly);
	int rval;
	tQSL_Location loc;
	wxString selname;
	char errbuf[512];
	do {
		TQSLGetStationNameDialog station_dial(this, help, wxDefaultPosition, false, title, okLabel, editonly);
		if (selname != wxT(""))
			station_dial.SelectName(selname);
		rval = station_dial.ShowModal();
		switch (rval) {
			case wxID_CANCEL:	// User hit Close
				return 0;
			case wxID_APPLY:	// User hit New
				check_tqsl_error(tqsl_initStationLocationCapture(&loc));
				selname = run_station_wizard(this, loc, help, false);
				check_tqsl_error(tqsl_endStationLocationCapture(&loc));
				frame->loc_tree->Build();
				break;
			case wxID_MORE:		// User hit Edit
		   		check_tqsl_error(tqsl_getStationLocation(&loc, station_dial.Selected().ToUTF8()));
				if (verify_cert(loc, true)) {	// Check if there is a certificate before editing
					check_tqsl_error(tqsl_getStationLocationErrors(loc, errbuf, sizeof(errbuf)));
					if (strlen(errbuf) > 0) {
						wxMessageBox(wxString::Format(wxT("%hs\nThe invalid data was ignored."), errbuf), wxT("Station Location data error"), wxOK|wxICON_EXCLAMATION, this);
					}
					char loccall[512];
					check_tqsl_error(tqsl_getLocationCallSign(loc, loccall, sizeof loccall));
					selname = run_station_wizard(this, loc, help, true, wxString::Format(wxT("Edit Station Location : %hs - %s"), loccall, station_dial.Selected().c_str()), station_dial.Selected());
					check_tqsl_error(tqsl_endStationLocationCapture(&loc));
				}
				break;
			case wxID_OK:		// User hit OK
		   		check_tqsl_error(tqsl_getStationLocation(&loc, station_dial.Selected().ToUTF8()));
				check_tqsl_error(tqsl_getStationLocationErrors(loc, errbuf, sizeof(errbuf)));
				if (strlen(errbuf) > 0) {
					wxMessageBox(wxString::Format(wxT("%hs\nThis should be corrected before signing a log file."), errbuf), wxT("Station Location data error"), wxOK|wxICON_EXCLAMATION, this);
				}
				break;
		}
	} while (rval != wxID_OK);
	return loc;
}

void MyFrame::CheckForUpdates(wxCommandEvent&) {
	tqslTrace("MyFrame::CheckForUpdates");
	DoUpdateCheck(false, false);
}

wxString GetUpdatePlatformString() {
	tqslTrace("GetUpdatePlatformString");
	wxString ret;
#if defined(_WIN32)
	#if defined(_WIN64)
		//this is 64 bit code already; if we are running we support 64
		ret = wxT("win64 win32");

	#else // this is not 64 bit code, but we are on windows
		// are we 64-bit compatible? if so prefer it
		BOOL val = false;
		typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
		LPFN_ISWOW64PROCESS fnIsWow64Process =
			(LPFN_ISWOW64PROCESS) GetProcAddress(GetModuleHandle(TEXT("kernel32")), "IsWow64Process");
		if (fnIsWow64Process != NULL) {
			fnIsWow64Process(GetCurrentProcess(), &val);
		}
		if(val) //32 bit running on 64 bit
			ret = wxT("win64 win32");
		else //just 32-bit only
			ret = wxT("win32");
	#endif

#elif defined(__APPLE__) && defined(__MACH__) //osx has universal binaries
	ret = wxT("osx");

#elif defined(__gnu_linux__)
	#if defined(__amd64__)
		ret = wxT("linux64 linux32 source");
	#elif defined(__i386__)
		ret = wxT("linux32 source");
	#else
		ret = wxT("source"); //source distribution is kosher on linux
	#endif
#else
	ret = wxT(""); //give them a homepage
#endif
	return ret;
}

// Class for encapsulating version information
class revLevel {
 public:
	revLevel(long _major = 0, long _minor = 0, long _patch = 0) {
		major = _major;
		minor = _minor;
		patch = _patch;
	}
	explicit revLevel(const wxString& _value) {
		wxString str = _value;
		str.Trim(true);
		str.Trim(false);
		wxStringTokenizer vers(str, wxT("."));
		wxString majorVer = vers.GetNextToken();
		wxString minorVer = vers.GetNextToken();
		wxString patchVer = vers.GetNextToken();
		if (majorVer.IsNumber()) {
			majorVer.ToLong(&major);
		} else {
			major = -1;
		}
		if (minorVer.IsNumber()) {
			minorVer.ToLong(&minor);
		} else {
			minor = -1;
		}
		if (patchVer.IsNumber()) {
			patchVer.ToLong(&patch);
		} else {
			patch = 0;
		}
	}
	wxString Value(void) {
		if (patch > 0)
			return wxString::Format(wxT("%d.%d.%d"), major, minor, patch);
		else
			return wxString::Format(wxT("%d.%d"), major, minor);
	}
	long major;
	long minor;
	long patch;
	bool operator >(const revLevel& other) {
		if (major > other.major) return true;
		if (major == other.major) {
			if (minor > other.minor) return true;
			if (minor == other.minor) {
				if (patch > other.patch) return true;
			}
		}
		return false;
	}
	bool operator  >=(const revLevel& other) {
		if (major > other.major) return true;
		if (major == other.major) {
			if (minor > other.minor) return true;
			if (minor == other.minor) {
				if (patch >= other.patch) return true;
			}
		}
		return false;
	}
};

class revInfo {
 public:
	revInfo(bool _noGUI = false, bool _silent = false) {
		noGUI = _noGUI;
		silent = _silent;
		error = false;
		message = false;
		programRev = newProgramRev = NULL;
		configRev = newConfigRev = NULL;
		mutex = new wxMutex;
		condition = new wxCondition(*mutex);
		mutex->Lock();
	}
	~revInfo() {
		if (programRev)
			delete programRev;
		if (newProgramRev)
			delete newProgramRev;
		if (configRev)
			delete configRev;
		if (newConfigRev)
			delete newConfigRev;
		if (condition)
			delete condition;
		if (mutex)
			delete mutex;
	}
	bool error;
	bool message;
	bool noGUI;
	bool silent;
	revLevel* programRev;
	revLevel* newProgramRev;
	revLevel* configRev;
	revLevel* newConfigRev;
	bool newProgram;
	bool newConfig;
	wxString errorText;
	wxString homepage;
	wxString url;
	wxMutex* mutex;
	wxCondition* condition;
};


class UpdateDialogMsgBox: public wxDialog {
 public:
	UpdateDialogMsgBox(wxWindow* parent, bool newProg, bool newConfig, revLevel* currentProgRev, revLevel* newProgRev,
			revLevel* currentConfigRev, revLevel* newConfigRev, wxString platformURL, wxString homepage)
			: wxDialog(parent, (wxWindowID)wxID_ANY, wxT("TQSL Update Available"), wxDefaultPosition, wxDefaultSize) {
		tqslTrace("UpdateDialogMsgBox::UpdateDialogMsgBox", "parent=%lx, newProg=%d, newConfig=%d, currentProgRev %s, newProgRev %s, currentConfigRev %s, newConfigRev=%s, platformURL=%s, homepage=%s", reinterpret_cast<void *>(parent), newProg, newConfig, S(currentProgRev->Value()), S(newProgRev->Value()), S(currentConfigRev->Value()), S(newConfigRev->Value()), S(platformURL), S(homepage));
		wxSizer* overall = new wxBoxSizer(wxVERTICAL);
		long flags = wxOK;
		if (newConfig)
			flags |= wxCANCEL;

		wxSizer* buttons = CreateButtonSizer(flags);
		wxString notice;
		if (newProg)
			notice = wxString::Format(wxT("A new TQSL release (V%s) is available!"), newProgRev->Value().c_str());
		else if (newConfig)
			notice = wxString::Format(wxT("A new TrustedQSL configuration file (V%s) is available!"), newConfigRev->Value().c_str());

		overall->Add(new wxStaticText(this, wxID_ANY, notice), 0, wxALIGN_CENTER_HORIZONTAL);

		if (newProg) {
			if (!platformURL.IsEmpty()) {
				wxSizer* thisline = new wxBoxSizer(wxHORIZONTAL);
				thisline->Add(new wxStaticText(this, wxID_ANY, wxT("Download from:")));
				thisline->Add(new wxHyperlinkCtrl(this, wxID_ANY, platformURL, platformURL));

				overall->AddSpacer(10);
				overall->Add(thisline);
			}

			if (!homepage.IsEmpty()) {
				wxSizer* thisline = new wxBoxSizer(wxHORIZONTAL);
				thisline->Add(new wxStaticText(this, wxID_ANY, wxT("More details at:")));
				thisline->Add(new wxHyperlinkCtrl(this, wxID_ANY, homepage, homepage));

				overall->AddSpacer(10);
				overall->Add(thisline);
			}
		}
		if (newConfig) {
			overall->AddSpacer(10);
			overall->Add(new wxStaticText(this, wxID_ANY, wxT("Click 'OK' to install the new configuration file, or Cancel to ignore it.")));
		}
		if (buttons) { //should always be here but documentation says to check
			overall->AddSpacer(10);
			overall->Add(buttons, 0, wxALIGN_CENTER_HORIZONTAL);
		}

		wxSizer* padding = new wxBoxSizer(wxVERTICAL);
		padding->Add(overall, 0, wxALL, 10);
		SetSizer(padding);
		Fit();
	}

 private:
};

void MyFrame::UpdateConfigFile() {
	tqslTrace("MyFrame::UpdateConfigFile()");
	wxConfig* config = reinterpret_cast<wxConfig *>(wxConfig::Get());
	wxString newConfigURL = config->Read(wxT("NewConfigURL"), DEFAULT_CONFIG_FILE_URL);
	curlReq = tqsl_curl_init("Config File Download Log", (const char *)newConfigURL.ToUTF8(), &curlLogFile, false);

	ConfigFileDownloadHandler handler(40000);

	curl_easy_setopt(curlReq, CURLOPT_WRITEFUNCTION, &ConfigFileDownloadHandler::recv);
	curl_easy_setopt(curlReq, CURLOPT_WRITEDATA, &handler);

	curl_easy_setopt(curlReq, CURLOPT_FAILONERROR, 1); //let us find out about a server issue

	char errorbuf[CURL_ERROR_SIZE];
	curl_easy_setopt(curlReq, CURLOPT_ERRORBUFFER, errorbuf);
	int retval = curl_easy_perform(curlReq);
	if (retval == CURLE_OK) {
		char *newconfig = reinterpret_cast<char *>(handler.s);
		wxString filename;
#ifdef _WIN32
		filename.Printf(wxT("%hs\\/config.tq6"), tQSL_BaseDir);
#else
		filename.Printf(wxT("%hs/config.tq6"), tQSL_BaseDir);
#endif
		FILE *configFile = fopen(tqslName(filename), "wb");
		if (!configFile) {
			wxMessageBox(wxString::Format(wxT("Can't open new configuration file %s: %hs"), filename.c_str(), strerror(errno)));
			return;
		}
		size_t left = handler.used;
		while (left > 0) {
			size_t written = fwrite(newconfig, 1, left, configFile);
			if (written == 0) {
				wxMessageBox(wxString::Format(wxT("Can't write new configuration file %s: %hs"), filename.c_str(), strerror(errno)));
				if (configFile) fclose(configFile);
				return;
			}
			left -= written;
		}
		if (fclose(configFile)) {
			wxMessageBox(wxString::Format(wxT("Error writing new configuration file %s: %hs"), filename.c_str(), strerror(errno)));
			return;
		}
		notifyData nd;
		if (tqsl_importTQSLFile(tqslName(filename), notifyImport, &nd)) {
			wxLogError(wxT("%hs"), tqsl_getErrorString());
		} else {
			wxMessageBox(wxT("Configuration file successfully updated"), wxT("Update Completed"), wxOK|wxICON_INFORMATION, this);
		}
	} else {
		if (diagFile) {
			fprintf(diagFile, "cURL Error during config file download: %s (%s)\n", curl_easy_strerror((CURLcode)retval), errorbuf);
		}
		if (curlLogFile) {
			fprintf(curlLogFile, "cURL Error during config file download: %s (%s)\n", curl_easy_strerror((CURLcode)retval), errorbuf);
		}
		if (retval == CURLE_COULDNT_RESOLVE_HOST || retval == CURLE_COULDNT_CONNECT) {
			wxLogMessage(wxT("Unable to update - either your Internet connection is down or LoTW is unreachable.\nPlease try again later."));
		} else if (retval == CURLE_WRITE_ERROR || retval == CURLE_SEND_ERROR || retval == CURLE_RECV_ERROR) {
			wxLogMessage(wxT("Unable to update. The nework is down or the LoTW site is too busy.\nPlease try again later."));
		} else if (retval == CURLE_SSL_CONNECT_ERROR) {
			wxLogMessage(wxT("Unable to connect to the update site.\nPlease try again later."));
		} else { // some other error
			wxMessageBox(wxString::Format(wxT("Error downloading new configuration file:\n%hs"), errorbuf), wxT("Update"), wxOK|wxICON_EXCLAMATION, this);
		}
	}
}

// Check if a certificate is still valid and current at LoTW
bool MyFrame::CheckCertStatus(long serial, wxString& result) {
	tqslTrace("MyFrame::CheckCertStatus()", "Serial=%ld", serial);
	wxConfig* config = reinterpret_cast<wxConfig *>(wxConfig::Get());

	wxString certCheckURL = config->Read(wxT("CertCheckURL"), DEFAULT_CERT_CHECK_URL);
	wxString certCheckRE = config->Read(wxT("StatusRegex"), DEFAULT_CERT_CHECK_RE);
	certCheckURL = certCheckURL + wxString::Format(wxT("%ld"), serial);

	curl_easy_setopt(curlReq, CURLOPT_URL, (const char *)certCheckURL.ToUTF8());

	FileUploadHandler handler;

	curl_easy_setopt(curlReq, CURLOPT_WRITEFUNCTION, &FileUploadHandler::recv);
	curl_easy_setopt(curlReq, CURLOPT_WRITEDATA, &handler);

	curl_easy_setopt(curlReq, CURLOPT_FAILONERROR, 1); //let us find out about a server issue

	char errorbuf[CURL_ERROR_SIZE];
	errorbuf[0] = '\0';
	curl_easy_setopt(curlReq, CURLOPT_ERRORBUFFER, errorbuf);
	int retval = curl_easy_perform(curlReq);
	result = wxString(wxT("Unknown"));
	bool ret = false;
	if (retval == CURLE_OK) {
                wxString checkresult = wxString::FromAscii(handler.s.c_str());

		wxRegEx checkStatusRE(certCheckRE);

                if (checkStatusRE.Matches(checkresult)) { // valid response
			result = checkStatusRE.GetMatch(checkresult, 1).Trim(true).Trim(false);
			ret = true;
		}
	} else {
		if (diagFile) {
			fprintf(diagFile, "cURL Error during cert status check: %s (%s)\n", curl_easy_strerror((CURLcode)retval), errorbuf);
		}
		if (curlLogFile) {
			fprintf(curlLogFile, "cURL Error during cert status check: %s (%s)\n", curl_easy_strerror((CURLcode)retval), errorbuf);
		}
		if (retval == CURLE_COULDNT_RESOLVE_HOST || retval == CURLE_COULDNT_CONNECT ||
		    retval == CURLE_WRITE_ERROR || retval == CURLE_SEND_ERROR || retval == CURLE_RECV_ERROR ||
		    retval == CURLE_SSL_CONNECT_ERROR) {
			// Network is down, unknown status
			return ret;
		}
	}
	return ret;
}

class expInfo {
 public:
	explicit expInfo(bool _noGUI = false) {
		noGUI = _noGUI;
		days = 0;
		callsign = NULL;
		error = false;
		mutex = new wxMutex;
		condition = new wxCondition(*mutex);
		mutex->Lock();
	}
	bool noGUI;
	int days;
	int index;
	char* callsign;
	bool error;
	wxString errorText;
	wxMutex* mutex;
	wxCondition* condition;
	~expInfo() {
		if (callsign) free(callsign);
		if (condition) delete condition;
		if (mutex) delete mutex;
	}
};

// Report an error back to the main thread
static void
report_error(expInfo **eip) {
	expInfo *ei = *eip;
	ei->error = true;
	ei->errorText = wxString::FromUTF8(tqsl_getErrorString());
	// Send the result back to the main thread
	wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, bg_expiring);
	event.SetClientData(ei);
	wxPostEvent(frame, event);
	ei->condition->Wait();		// stalls here until the main thread resumes the thread
	ei->mutex->Unlock();
	delete ei;
	*eip = new expInfo;
}

// Check for certificates expiring in the next nn (default 60) days
void
MyFrame::DoCheckExpiringCerts(bool noGUI) {
	expInfo *ei = new expInfo;
	ei->noGUI = noGUI;

	curl_easy_cleanup(curlReq);
	curlReq = tqsl_curl_init("Certificate Check Log", "https://lotw.arrl.org", &curlLogFile, false);
	get_certlist("", 0, false, false, false);
	if (ncerts == 0) return;

	long expireDays = DEFAULT_CERT_WARNING;
	wxConfig::Get()->Read(wxT("CertWarnDays"), &expireDays);
	// Get today's date
	time_t t = time(0);
	struct tm *tm = gmtime(&t);
	tQSL_Date d;
	d.year = tm->tm_year + 1900;
	d.month = tm->tm_mon + 1;
	d.day = tm->tm_mday;
	tQSL_Date exp;

	for (int i = 0; i < ncerts; i ++) {
		char callsign[64];
		if (tqsl_getCertificateCallSign(certlist[i], callsign, sizeof callsign)) {
			report_error(&ei);
			continue;
		}
		int keyonly, pending;
		keyonly = pending = 0;
		if (tqsl_getCertificateKeyOnly(certlist[i], &keyonly)) {
			report_error(&ei);
			continue;
		}
		long serial = 0;
		wxString status = wxString(wxT("KeyOnly"));
		if (!keyonly) {
			if (tqsl_getCertificateSerial(certlist[i], &serial)) {
				report_error(&ei);
				continue;
			}
			CheckCertStatus(serial, status);
			if (tqsl_setCertificateStatus(serial, (const char *)status.ToUTF8())) {
				report_error(&ei);
				continue;
			}
		}
		wxString reqPending = wxConfig::Get()->Read(wxT("RequestPending"));
		wxStringTokenizer tkz(reqPending, wxT(","));
		while (tkz.HasMoreTokens()) {
			wxString pend = tkz.GetNextToken();
                        if (pend == wxString::FromUTF8(callsign)) {
				pending = true;
				break;
			}
		}

		if (keyonly || pending)
			continue;

		if (0 == tqsl_getCertificateNotAfterDate(certlist[i], &exp)) {
			int days_left;
			tqsl_subtractDates(&d, &exp, &days_left);
			if (days_left < expireDays) {
				ei->days = days_left;
				ei->callsign = strdup(callsign);
				ei->index = i;
				// Send the result back to the main thread
				wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, bg_expiring);
				event.SetClientData(ei);
				wxPostEvent(frame, event);
				ei->condition->Wait();
				ei->mutex->Unlock();
				delete ei;
				ei = new expInfo;
				ei->noGUI = noGUI;
			}
		}
	}
	ei->mutex->Unlock();
	delete ei;
	free_certlist();
	curl_easy_cleanup(curlReq);
	if (curlLogFile) {
		fclose(curlLogFile);
		curlLogFile = NULL;
	}
	return;
}

void
MyFrame::OnExpiredCertFound(wxCommandEvent& event) {
	expInfo *ei = reinterpret_cast<expInfo *>(event.GetClientData());
	if (ei->error) {
		if (ei->noGUI) {
			wxLogError(ei->errorText);
		} else {
			wxMessageBox(wxString(wxT("Error checking for expired callsign certificates:")) + ei->errorText,
				     wxT("Check Error"), wxOK|wxICON_EXCLAMATION, this);
		}
	} else if (ei->noGUI) {
		wxLogMessage(wxT("The certificate for %hs expires in %d days."),
			ei->callsign, ei->days);
	} else {
		if (wxMessageBox(
			wxString::Format(wxT("The certificate for %hs expires in %d days\n")
					wxT("Do you want to renew it now?"),
					ei->callsign, ei->days),
					wxT("Certificate Expiring"), wxYES_NO|wxICON_QUESTION, this) == wxYES) {
				// Select the certificate in the tree
				cert_tree->SelectCert(certlist[ei->index]);
				// Then start the renewal
				wxCommandEvent dummy;
				CRQWizardRenew(dummy);
		}
	}
	// Tell the background thread that it's OK to continue
	wxMutexLocker lock(*ei->mutex);
	ei->condition->Signal();
}

void
MyFrame::OnUpdateCheckDone(wxCommandEvent& event) {
	revInfo *ri = reinterpret_cast<revInfo *>(event.GetClientData());
	if (!ri) return;
	if (ri->error) {
		if (!ri->silent && !ri->noGUI)
			wxLogMessage(ri->errorText);
		wxMutexLocker lock(*ri->mutex);
		ri->condition->Signal();
		return;
	}
	if (ri->message) {
		if (!ri->silent && !ri->noGUI)
			wxMessageBox(ri->errorText, wxT("Update"), wxOK|wxICON_EXCLAMATION, this);
		wxMutexLocker lock(*ri->mutex);
		ri->condition->Signal();
		return;
	}
	if (ri->newProgram) {
		if (ri->noGUI) {
			wxLogMessage(wxT("A new TQSL release (V%s) is available."), ri->newProgramRev->Value().c_str());
		} else {
			//will create ("homepage"->"") if none there, which is what we'd be checking for anyway
			UpdateDialogMsgBox msg(this, true, false, ri->programRev, ri->newProgramRev,
					ri->configRev, ri->newConfigRev, ri->url, ri->homepage);

			msg.ShowModal();
		}
	}
	if (ri->newConfig) {
		if (ri->noGUI) {
			wxLogMessage(wxT("A new TrustedQSL configuration file (V%s) is available."), ri->newConfigRev->Value().c_str());
		} else {
			UpdateDialogMsgBox msg(this, false, true, ri->programRev, ri->newProgramRev,
					ri->configRev, ri->newConfigRev, wxT(""), wxT(""));

			if (msg.ShowModal() == wxID_OK) {
				UpdateConfigFile();
			}
		}
	}

	if (!ri->newProgram && !ri->newConfig) {
		if (!ri->silent && !ri->noGUI) {
			wxMessageBox(wxString::Format(wxT("Your system is up to date!\nTQSL Version %hs and Configuration Version %s\nare the newest available"), VERSION, ri->configRev->Value().c_str()), wxT("No Updates"), wxOK|wxICON_INFORMATION, this);
		}
	}
	// Tell the background thread that it's OK to continue
	wxMutexLocker lock(*ri->mutex);
	ri->condition->Signal();
}

// The macro for declaring a hash map defines a couple of typedefs
// that it never uses. Current GCC warns about those. The pragma
// below suppresses those warnings for those.
#if !defined(__APPLE__) && !defined(_WIN32)
	#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#endif
void
MyFrame::DoCheckForUpdates(bool silent, bool noGUI) {
	tqslTrace("MyFrame::DoCheckForUpdates", "silent=%d noGUI=%d", silent, noGUI);
	wxConfig* config = reinterpret_cast<wxConfig *>(wxConfig::Get());

	wxString lastUpdateTime = config->Read(wxT("UpdateCheckTime"));
	int numdays = config->Read(wxT("UpdateCheckInterval"), 1); // in days

	bool check = true;
	if (!lastUpdateTime.IsEmpty()) {
		wxDateTime lastcheck; lastcheck.ParseFormat(lastUpdateTime, wxT("%Y-%m-%d"));
		lastcheck+=wxDateSpan::Days(numdays); // x days from when we checked
		if (lastcheck > wxDateTime::Today()) //if we checked less than x days ago
			check = false;  // don't check again
	} // else no stored value, means check

	if (!silent) check = true; //unless the user explicitly asked

	if (!check) return;	//if we really weren't supposed to check, get out of here

	revInfo* ri = new revInfo;
	ri->noGUI = noGUI;
	ri->silent = silent;
	ri->programRev = new revLevel(wxT(VERSION));

	int currentConfigMajor, currentConfigMinor;
	tqsl_getConfigVersion(&currentConfigMajor, &currentConfigMinor);
	ri->configRev = new revLevel(currentConfigMajor, currentConfigMinor, 0);		// config files don't have patch levels

	wxString updateURL = config->Read(wxT("UpdateURL"), DEFAULT_UPD_URL);

	curlReq = tqsl_curl_init("Version Check Log", (const char*)updateURL.ToUTF8(), &curlLogFile, true);

	//the following allow us to analyze our file

	FileUploadHandler handler;

	curl_easy_setopt(curlReq, CURLOPT_WRITEFUNCTION, &FileUploadHandler::recv);
	curl_easy_setopt(curlReq, CURLOPT_WRITEDATA, &handler);

	if(silent) { // if there's a problem, we don't want the program to hang while we're starting it
		curl_easy_setopt(curlReq, CURLOPT_CONNECTTIMEOUT, 120);
	}

	curl_easy_setopt(curlReq, CURLOPT_FAILONERROR, 1); //let us find out about a server issue

	char errorbuf[CURL_ERROR_SIZE];
	curl_easy_setopt(curlReq, CURLOPT_ERRORBUFFER, errorbuf);

	tqslTrace("MyFrame::DoCheckForUpdates", "calling curl_easy_perform");
	int retval = curl_easy_perform(curlReq);
	tqslTrace("MyFrame::DoCheckForUpdates", "Program rev check returns %d", retval);
	if (retval == CURLE_OK) {
		tqslTrace("MyFrame::DoCheckForUpdates", "Program rev returns %d chars, %s", handler.s.size(), handler.s.c_str());
		// Add the config.xml text to the result
		wxString configURL = config->Read(wxT("ConfigFileVerURL"), DEFAULT_UPD_CONFIG_URL);
		curl_easy_setopt(curlReq, CURLOPT_URL, (const char*)configURL.ToUTF8());

		retval = curl_easy_perform(curlReq);
		if (retval == CURLE_OK) {
			tqslTrace("MyFrame::DoCheckForUpdates", "Prog + Config rev returns %d chars, %s", handler.s.size(), handler.s.c_str());
			wxString result = wxString::FromAscii(handler.s.c_str());
			wxString url;
			WX_DECLARE_STRING_HASH_MAP(wxString, URLHashMap);
			URLHashMap map;
			ri->newProgramRev = NULL;
			ri->newConfigRev = NULL;

			wxStringTokenizer urls(result, wxT("\n"));
			wxString onlinever;
			while(urls.HasMoreTokens()) {
				wxString header = urls.GetNextToken().Trim();
				if (header.StartsWith(wxT("TQSLVERSION;"), &onlinever)) {
					ri->newProgramRev = new revLevel(onlinever);
				} else if (header.IsEmpty()) {
					continue; //blank line
				} else if (header[0] == '#') {
					continue; //comments
				} else if (header.StartsWith(wxT("config.xml"), &onlinever)) {
					onlinever.Replace(wxT(":"), wxT(""));
					onlinever.Replace(wxT("Version"), wxT(""));
					onlinever.Trim(true);
					onlinever.Trim(false);
					ri->newConfigRev = new revLevel(onlinever);
				} else {
					int sep = header.Find(';'); //; is invalid in URLs
					if (sep == wxNOT_FOUND) continue; //malformed string
					wxString plat = header.Left(sep);
					wxString url = header.Right(header.size()-sep-1);
					map[plat]=url;
				}
			}
#ifdef TQSL_TEST_BUILD
			ri->newProgram = ri->newProgramRev ? (*ri->newProgramRev >= *ri->programRev) : false;
#else
			ri->newProgram = ri->newProgramRev ? (*ri->newProgramRev > *ri->programRev) : false;
#endif
			ri->newConfig = ri->newConfigRev ? (*ri->newConfigRev > *ri->configRev) : false;
			if (ri->newProgram) {
				wxString ourPlatURL; //empty by default (we check against this later)

				wxStringTokenizer plats(GetUpdatePlatformString(), wxT(" "));
				while(plats.HasMoreTokens()) {
					wxString tok = plats.GetNextToken();
					//see if this token is here
					if (map.count(tok)) { ourPlatURL=map[tok]; break; }
				}
				ri->homepage = map[wxT("homepage")];
				ri->url = ourPlatURL;
			}
		} else {
			if (diagFile) {
				fprintf(diagFile, "cURL Error during config file version check: %d : %s (%s)\n", retval, curl_easy_strerror((CURLcode)retval), errorbuf);
			}
			if (curlLogFile) {
				fprintf(curlLogFile, "cURL Error during config file version check: %s (%s)\n", curl_easy_strerror((CURLcode)retval), errorbuf);
			}
			if (retval == CURLE_COULDNT_RESOLVE_HOST || retval == CURLE_COULDNT_CONNECT) {
				ri->error = true;
				ri->errorText = wxString::FromUTF8("Unable to check for updates - either your Internet connection is down or LoTW is unreachable.\nPlease try again later.");
			} else if (retval == CURLE_WRITE_ERROR || retval == CURLE_SEND_ERROR || retval == CURLE_RECV_ERROR) {
				ri->error = true;
				ri->errorText = wxString::FromUTF8("Unable to check for updates. The nework is down or the LoTW site is too busy.\nPlease try again later.");
			} else if (retval == CURLE_SSL_CONNECT_ERROR) {
				ri->error = true;
				ri->errorText = wxString::FromUTF8("Unable to connect to the update site.\nPlease try again later.");
			} else { // some other error
				ri->message = true;
				ri->errorText = wxString::Format(wxT("Error downloading new version information:\n%hs"), errorbuf);
			}
		}
	} else {
		if (diagFile) {
			fprintf(diagFile, "cURL Error during program revision check: %d: %s (%s)\n", retval, curl_easy_strerror((CURLcode)retval), errorbuf);
		}
		if (curlLogFile) {
			fprintf(curlLogFile, "cURL Error during program revision check: %s (%s)\n", curl_easy_strerror((CURLcode)retval), errorbuf);
		}
		if (retval == CURLE_COULDNT_RESOLVE_HOST || retval == CURLE_COULDNT_CONNECT) {
			ri->error = true;
			ri->errorText = wxString::FromUTF8("Unable to check for updates - either your Internet connection is down or LoTW is unreachable.\nPlease try again later.");
		} else if (retval == CURLE_WRITE_ERROR || retval == CURLE_SEND_ERROR || retval == CURLE_RECV_ERROR) {
			ri->error = true;
			ri->errorText = wxString::FromUTF8("Unable to check for updates. The nework is down or the LoTW site is too busy.\nPlease try again later.");
		} else if (retval == CURLE_SSL_CONNECT_ERROR) {
			ri->error = true;
			ri->errorText = wxString::FromUTF8("Unable to connect to the update site.\nPlease try again later.");
		} else { // some other error
			ri->message = true;
			ri->errorText = wxString::Format(wxT("Error downloading update version information:\n%hs"), errorbuf);
		}
	}

	// Send the result back to the main thread
	wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, bg_updateCheck);
	event.SetClientData(ri);
	wxPostEvent(frame, event);
	ri->condition->Wait();
	ri->mutex->Unlock();
	delete ri;
	if (curlReq) curl_easy_cleanup(curlReq);
	if (curlLogFile) fclose(curlLogFile);
	curlReq = NULL;
	curlLogFile = NULL;

	// we checked today, and whatever the result, no need to (automatically) check again until the next interval

	config->Write(wxT("UpdateCheckTime"), wxDateTime::Today().FormatISODate());

	// After update check, validate user certificates
	DoCheckExpiringCerts(noGUI);
	return;
}
#if !defined(__APPLE__) && !defined(_WIN32)
	#pragma GCC diagnostic warning "-Wunused-local-typedefs"
#endif

static void
wx_tokens(const wxString& str, vector<wxString> &toks) {
	size_t idx = 0;
	size_t newidx;
	wxString tok;
	do {
		newidx = str.find(wxT(" "), idx);
		if (newidx != wxString::npos) {
			toks.push_back(str.Mid(idx, newidx - idx));
			idx = newidx + 1;
		}
	} while (newidx != wxString::npos);
	if (str.Mid(idx) != wxT(""))
		toks.push_back(str.Mid(idx));
}

void
MyFrame::ImportQSODataFile(wxCommandEvent& event) {
	tqslTrace("MyFrame::ImportQSODataFile");
	wxString infile;

	// Does the user have any certificates?
	get_certlist("", 0, false, false, true);
	if (ncerts == 0) {
		wxMessageBox(wxT("You have no callsign certificates to use to sign a log file.\n")
			   wxT("Please install a callsign certificate then try again."), wxT("No Callsign Certificates"),
			   wxOK|wxICON_EXCLAMATION, this);
		free_certlist();
		return;
	}
	free_certlist();
	try {
		bool compressed = (event.GetId() == tm_f_import_compress || event.GetId() == tl_Save);

		wxConfig *config = reinterpret_cast<wxConfig *>(wxConfig::Get());
		// Get input file

		wxString path = config->Read(wxT("ImportPath"), wxString(wxT("")));
		wxString defext = config->Read(wxT("ImportExtension"), wxString(wxT("adi"))).Lower();
		bool defFound = false;
		// Construct filter string for file-open dialog
		wxString filter = wxT("All files (*.*)|*.*");
		vector<wxString> exts;
		wxString file_exts = config->Read(wxT("ADIFFiles"), wxString(DEFAULT_ADIF_FILES));
		wx_tokens(file_exts, exts);
		wxString extList;
		for (int i = 0; i < static_cast<int>(exts.size()); i++) {
			extList += wxT("*.") + exts[i] + wxT(";");
			if (exts[i] == defext)
				defFound = true;
		}
		extList.RemoveLast();		// Remove the trailing semicolon
		filter += wxT("|ADIF files (") + extList + wxT(")|") + extList;

		exts.clear();
		extList.Clear();
		file_exts = config->Read(wxT("CabrilloFiles"), wxString(DEFAULT_CABRILLO_FILES));
		wx_tokens(file_exts, exts);
		for (int i = 0; i < static_cast<int>(exts.size()); i++) {
			extList += wxT("*.") + exts[i] + wxT(";");
			if (exts[i] == defext)
				defFound = true;
		}
		extList.RemoveLast();
		filter += wxT("|Cabrillo files (") + extList + wxT(")|") + extList;
		if (defext.IsEmpty() || !defFound)
			defext = wxString(wxT("adi"));
		infile = wxFileSelector(wxT("Select file to Sign"), path, wxT(""), defext, filter,
			wxFD_OPEN|wxFD_FILE_MUST_EXIST, this);
		if (infile == wxT(""))
			return;
		wxString inPath;
		wxString inExt;
		wxSplitPath(infile.c_str(), &inPath, NULL, &inExt);
		inExt.Lower();
		config->Write(wxT("ImportPath"), inPath);
		config->Write(wxT("ImportExtension"), inExt);
		// Get output file
		wxString basename;
		wxSplitPath(infile.c_str(), 0, &basename, 0);
		path = wxConfig::Get()->Read(wxT("ExportPath"), wxString(wxT("")));
		wxString deftype = compressed ? wxT("tq8") : wxT("tq7");
		filter = compressed ? wxT("TQSL compressed data files (*.tq8)|*.tq8")
			: wxT("TQSL data files (*.tq7)|*.tq7");
		basename += wxT(".") + deftype;
		wxString outfile = wxFileSelector(wxT("Select file to write to"),
			path, basename, deftype, filter + wxT("|All files (*.*)|*.*"),
			wxFD_SAVE|wxFD_OVERWRITE_PROMPT, this);
		if (outfile == wxT(""))
			return;
		config->Write(wxT("ExportPath"), wxPathOnly(outfile));

		tQSL_Location loc = SelectStationLocation(wxT("Select Station Location for Signing"));
		if (loc == 0)
			return;

		if (!verify_cert(loc, false))
			return;
		char callsign[40];
		char loc_name[256];
		int dxccnum;
		check_tqsl_error(tqsl_getLocationCallSign(loc, callsign, sizeof callsign));
		check_tqsl_error(tqsl_getLocationDXCCEntity(loc, &dxccnum));
		check_tqsl_error(tqsl_getStationLocationCaptureName(loc, loc_name, sizeof loc_name));
		DXCC dxcc;
		dxcc.getByEntity(dxccnum);
		tqslTrace("MyFrame::ImportQSODataFile", "file=%s location %hs, call %hs dxcc %hs",
				S(infile), loc_name, callsign, dxcc.name());
		if (wxMessageBox(wxString::Format(wxT("The file (%s) will be signed using:\n"
				 wxT("Station Location: %hs\nCall sign: %hs\nDXCC: %hs\nIs this correct?")), infile.c_str(), loc_name,
			callsign, dxcc.name()), wxT("TQSL - Confirm signing"), wxYES_NO, this) == wxYES)
			ConvertLogFile(loc, infile, outfile, compressed);
		else
			wxLogMessage(wxT("Signing abandoned"));
	}
	catch(TQSLException& x) {
		wxString s;
		wxString err = wxString::FromUTF8(x.what());
		if (err.Find(infile) == wxNOT_FOUND) {
			if (infile != wxT(""))
				s = infile + wxT(": ");
		}
		s += err;
		wxLogError(wxT("%s"), (const char *)s.c_str());
	}
	free_certlist();
	return;
}

void
MyFrame::UploadQSODataFile(wxCommandEvent& event) {
	tqslTrace("MyFrame::UploadQSODataFile");
	wxString infile;
	// Does the user have any certificates?
	get_certlist("", 0, false, false, true);
	if (ncerts == 0) {
		wxMessageBox(wxT("You have no callsign certificates to use to sign a log file.\n")
			   wxT("Please install a callsign certificate then try again."), wxT("No Callsign Certificates"),
			   wxOK|wxICON_EXCLAMATION, this);
		free_certlist();
		return;
	}
	free_certlist();
	try {
		wxConfig *config = reinterpret_cast<wxConfig *>(wxConfig::Get());
		// Get input file
		wxString path = config->Read(wxT("ImportPath"), wxString(wxT("")));
		wxString defext = config->Read(wxT("ImportExtension"), wxString(wxT("adi"))).Lower();
		bool defFound = false;

		// Construct filter string for file-open dialog
		wxString filter = wxT("All files (*.*)|*.*");
		vector<wxString> exts;
		wxString file_exts = config->Read(wxT("ADIFFiles"), wxString(DEFAULT_ADIF_FILES));
		wx_tokens(file_exts, exts);
		wxString extList;
		for (int i = 0; i < static_cast<int>(exts.size()); i++) {
			extList += wxT("*.") + exts[i] + wxT(";");
			if (exts[i] == defext)
				defFound = true;
		}
		extList.RemoveLast();		// Remove the trailing semicolon
		filter += wxT("|ADIF files (") + extList + wxT(")|") + extList;

		exts.clear();
		extList.Clear();
		file_exts = config->Read(wxT("CabrilloFiles"), wxString(DEFAULT_CABRILLO_FILES));
		wx_tokens(file_exts, exts);
		for (int i = 0; i < static_cast<int>(exts.size()); i++) {
			extList += wxT("*.") + exts[i] + wxT(";");
			if (exts[i] == defext)
				defFound = true;
		}
		extList.RemoveLast();
		filter += wxT("|Cabrillo files (") + extList + wxT(")|") + extList;
		if (defext.IsEmpty() || !defFound)
			defext = wxString(wxT("adi"));
		infile = wxFileSelector(wxT("Select file to Sign"), path, wxT(""), defext, filter,
			wxFD_OPEN|wxFD_FILE_MUST_EXIST, this);
		if (infile == wxT(""))
			return;
		wxString inPath;
		wxString inExt;
		wxSplitPath(infile.c_str(), &inPath, NULL, &inExt);
		inExt.Lower();
		config->Write(wxT("ImportPath"), inPath);
		config->Write(wxT("ImportExtension"), inExt);

		// Get Station Location
		tQSL_Location loc = SelectStationLocation(wxT("Select Station Location for Signing"));
		if (loc == 0)
			return;

		char callsign[40];
		char loc_name[256];
		int dxccnum;
		check_tqsl_error(tqsl_getLocationCallSign(loc, callsign, sizeof callsign));
		check_tqsl_error(tqsl_getLocationDXCCEntity(loc, &dxccnum));
		check_tqsl_error(tqsl_getStationLocationCaptureName(loc, loc_name, sizeof loc_name));
		DXCC dxcc;
		dxcc.getByEntity(dxccnum);
		tqslTrace("MyFrame::UploadQSODataFile", "file=%s location %hs, call %hs dxcc %hs",
				S(infile), loc_name, callsign, dxcc.name());
		if (wxMessageBox(wxString::Format(wxT("The file (%s) will be signed and uploaded using:\n"
				wxT("Station Location: %hs\nCall sign: %hs\nDXCC: %hs\nIs this correct?")), infile.c_str(), loc_name,
			callsign, dxcc.name()), wxT("TQSL - Confirm signing"), wxYES_NO, this) == wxYES)
			UploadLogFile(loc, infile);
		else
			wxLogMessage(wxT("Signing abandoned"));
	}
	catch(TQSLException& x) {
		wxString s;
		wxString err = wxString::FromUTF8(x.what());
		if (err.Find(infile) == wxNOT_FOUND) {
			if (infile != wxT(""))
				s = infile + wxT(": ");
		}
		s += err;
		wxLogError(wxT("%s"), (const char *)s.c_str());
	}
	free_certlist();
}

void MyFrame::OnPreferences(wxCommandEvent& WXUNUSED(event)) {
	tqslTrace("MyFrame::OnPreferences");
	Preferences* dial = new Preferences(this, help);
	dial->Show(true);
	file_menu->Enable(tm_f_preferences, false);
}

class TQSLConfig {
 public:
	TQSLConfig() {
		callSign = "";
		serial = 0;
		dxcc = 0;
		dupes = 0;
		elementBody = wxT("");
		locstring = wxT("");
		config = NULL;
		outstr = NULL;
		conv = NULL;
	}
	void SaveSettings(gzFile* out, wxString appname);
	void RestoreCert(void);
	void RestoreConfig(const gzFile& in);
	void ParseLocations(gzFile* out, const tQSL_StationDataEnc loc);
	wxConfig *config;
	long serial;
	int dxcc;
	int dupes;
	string callSign;
	wxString signedCert;
	wxString privateKey;
	wxString elementBody;
	wxString locstring;
	gzFile* outstr;
	tQSL_Converter conv;

 private:
	static void xml_restore_start(void *data, const XML_Char *name, const XML_Char **atts);
	static void xml_restore_end(void *data, const XML_Char *name);
	static void xml_text(void *data, const XML_Char *text, int len);
	static void xml_location_start(void *data, const XML_Char *name, const XML_Char **atts);
	static void xml_location_end(void *data, const XML_Char *name);
};

// Save the user's configuration settings - appname is the
// application name (tqslapp)

void TQSLConfig::SaveSettings(gzFile* out, wxString appname) {
	tqslTrace("TQSLConfig::SaveSettings", "appname=%s", S(appname));
	config = new wxConfig(appname);
	wxString name, gname;
	long	context;
	wxString svalue;
	long	lvalue;
	bool	bvalue;
	double	dvalue;
	wxArrayString groupNames;

	tqslTrace("TQSLConfig::SaveSettings", "... init groups");
	groupNames.Add(wxT("/"));
	bool more = config->GetFirstGroup(gname, context);
	while (more) {
		tqslTrace("TQSLConfig::SaveSettings", "... add group %s", S(name));
		groupNames.Add(wxT("/") + gname);
		more = config->GetNextGroup(gname, context);
	}
	tqslTrace("TQSLConfig::SaveSettings", "... groups done.");

	for (unsigned i = 0; i < groupNames.GetCount(); i++) {
		tqslTrace("TQSLConfig::SaveSettings", "Group %d setting path %s", i, S(groupNames[i]));
		config->SetPath(groupNames[i]);
		more = config->GetFirstEntry(name, context);
		while (more) {
			tqslTrace("TQSLConfig::SaveSettings", "name=%s", S(name));
			if (name.IsEmpty()) {
				more = config->GetNextEntry(name, context);
				continue;
			}
			gzprintf(*out, "<Setting name=\"%s\" group=\"%s\" ", (const char *)name.ToUTF8(), (const char *)groupNames[i].ToUTF8());
			wxConfigBase::EntryType etype = config->GetEntryType(name);
			switch (etype) {
                                case wxConfigBase::Type_Unknown:
                                case wxConfigBase::Type_String:
					config->Read(name, &svalue);
					urlEncode(svalue);
					gzprintf(*out, "Type=\"String\" Value=\"%s\"/>\n", (const char *)svalue.ToUTF8());
					break;
                                case wxConfigBase::Type_Boolean:
					config->Read(name, &bvalue);
					if (bvalue)
						gzprintf(*out, "Type=\"Bool\" Value=\"true\"/>\n");
					else
						gzprintf(*out, "Type=\"Bool\" Value=\"false\"/>\n");
					break;
                                case wxConfigBase::Type_Integer:
					config->Read(name, &lvalue);
					gzprintf(*out, "Type=\"Int\" Value=\"%d\"/>\n", lvalue);
					break;
                                case wxConfigBase::Type_Float:
					config->Read(name, &dvalue);
					gzprintf(*out, "Type=\"Float\" Value=\"%f\"/>\n", dvalue);
					break;
			}
			more = config->GetNextEntry(name, context);
		}
	}
	tqslTrace("TQSLConfig::SaveSettings", "Done.");
	config->SetPath(wxT("/"));

	return;
}

void
MyFrame::BackupConfig(const wxString& filename, bool quiet) {
	tqslTrace("MyFrame::BackupConfig", "filename=%s, quiet=%d", S(filename), quiet);
	int i;
	wxBusyCursor wait;
	if (lock_db(false) < 0) {
		if (quiet)			// If there's an active signing thread,
			return;			// then exit without taking a backup.
		wxSafeYield();
		wxLogMessage(wxT("TQSL must wait for other running copies of TQSL to exit before backing up..."));
		wxSafeYield();
		lock_db(true);
	}
	try {
		gzFile out = 0;
		out = gzopen(tqslName(filename), "wb9");
		if (!out) {
			wxLogError(wxT("Error opening save file %s: %hs"), filename.c_str(), strerror(errno));
			return;
		}
		TQSLConfig* conf = new TQSLConfig();

		gzprintf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<TQSL_Configuration>\n");
		gzprintf(out, "<!-- Warning! If you directly edit this file, you are responsible for its content.\n");
		gzprintf(out, "The ARRL's LoTW Help Desk will be unable to assist you. -->\n");
		gzprintf(out, "<Certificates>\n");

		if (!quiet) {
			wxLogMessage(wxT("Saving callsign certificates"));
		} else {
			tqslTrace("MyFrame::BackupConfig", "Saving callsign certificates");
		}
		wxSafeYield(frame);
		int ncerts;
		char buf[8192];
		// Save root certificates
		check_tqsl_error(tqsl_selectCACertificates(&certlist, &ncerts, "root"));
		for (i = 0; i < ncerts; i++) {
			gzprintf(out, "<RootCert>\n");
			check_tqsl_error(tqsl_getCertificateEncoded(certlist[i], buf, sizeof buf));
			gzwrite(out, buf, strlen(buf));
			gzprintf(out, "</RootCert>\n");
			tqsl_freeCertificate(certlist[i]);
		}
		// Save CA certificates
		check_tqsl_error(tqsl_selectCACertificates(&certlist, &ncerts, "authorities"));
		for (i = 0; i < ncerts; i++) {
			gzprintf(out, "<CACert>\n");
			check_tqsl_error(tqsl_getCertificateEncoded(certlist[i], buf, sizeof buf));
			gzwrite(out, buf, strlen(buf));
			gzprintf(out, "</CACert>\n");
			tqsl_freeCertificate(certlist[i]);
		}
		tqsl_selectCertificates(&certlist, &ncerts, 0, 0, 0, 0, TQSL_SELECT_CERT_WITHKEYS | TQSL_SELECT_CERT_EXPIRED | TQSL_SELECT_CERT_SUPERCEDED);
		for (i = 0; i < ncerts; i++) {
			char callsign[64];
			long serial = 0;
			int dxcc = 0;
			int keyonly;
			check_tqsl_error(tqsl_getCertificateKeyOnly(certlist[i], &keyonly));
			check_tqsl_error(tqsl_getCertificateCallSign(certlist[i], callsign, sizeof callsign));
			if (!keyonly) {
				check_tqsl_error(tqsl_getCertificateSerial(certlist[i], &serial));
			}
			check_tqsl_error(tqsl_getCertificateDXCCEntity(certlist[i], &dxcc));
			if (!quiet) {
				wxLogMessage(wxT("\tSaving callsign certificate for %hs"), callsign);
			}
			gzprintf(out, "<UserCert CallSign=\"%s\" dxcc=\"%d\" serial=\"%d\">\n", callsign, dxcc, serial);
			if (!keyonly) {
				gzprintf(out, "<SignedCert>\n");
				check_tqsl_error(tqsl_getCertificateEncoded(certlist[i], buf, sizeof buf));
				gzwrite(out, buf, strlen(buf));
				gzprintf(out, "</SignedCert>\n");
			}
			gzprintf(out, "<PrivateKey>\n");
			check_tqsl_error(tqsl_getKeyEncoded(certlist[i], buf, sizeof buf));
			gzwrite(out, buf, strlen(buf));
			gzprintf(out, "</PrivateKey>\n</UserCert>\n");
			tqsl_freeCertificate(certlist[i]);
		}
		gzprintf(out, "</Certificates>\n");
		gzprintf(out, "<Locations>\n");
		if (!quiet) {
			wxLogMessage(wxT("Saving Station Locations"));
		} else {
			tqslTrace("MyFrame::BackupConfig", "Saving Station Locations");
		}
		wxSafeYield(frame);
		tQSL_StationDataEnc sdbuf = NULL;
		check_tqsl_error(tqsl_getStationDataEnc(&sdbuf));
		TQSLConfig* parser = new TQSLConfig();
		if (sdbuf)
			parser->ParseLocations(&out, sdbuf);
		check_tqsl_error(tqsl_freeStationDataEnc(sdbuf));
		gzprintf(out, "</Locations>\n");

		if (!quiet) {
			wxLogMessage(wxT("Saving TQSL Preferences"));
		} else {
			tqslTrace("MyFrame::BackupConfig", "Saving TQSL Preferences - out=0x%lx", reinterpret_cast<void *>(out));
		}
		wxSafeYield(frame);
		gzprintf(out, "<TQSLSettings>\n");
		conf->SaveSettings(&out, wxT("tqslapp"));
		tqslTrace("MyFrame::BackupConfig", "Done with settings. out=0x%lx", reinterpret_cast<void *>(out));
		gzprintf(out, "</TQSLSettings>\n");

		if (!quiet) {
			wxLogMessage(wxT("Saving QSOs"));
		} else {
			tqslTrace("MyFrame::BackupConfig", "Saving QSOs");
		}

		wxSafeYield(frame);
		tQSL_Converter conv = 0;
		check_tqsl_error(tqsl_beginConverter(&conv));
		tqslTrace("MyFrame::BackupConfig", "beginConverter call success");
		gzprintf(out, "<DupeDb>\n");

		char dupekey[256];
		char dupedata[10];
		int count = 0;
		while (true) {
			int status = tqsl_getDuplicateRecords(conv, dupekey, dupedata, sizeof(dupekey));
			if (status == -1)		// End of file
				break;
			check_tqsl_error(status);
			gzprintf(out, "<Dupe key=\"%s\" />\n", dupekey);
			if ((count++ % 100000) == 0) {
				wxSafeYield(frame);
			}
		}
		gzprintf(out, "</DupeDb>\n");
		tqsl_converterCommit(conv);
		tqsl_endConverter(&conv);
		unlock_db();
		tqslTrace("MyFrame::BackupConfig", "Dupes db saved OK");

		gzprintf(out, "</TQSL_Configuration>\n");

		gzclose(out);
		if (!quiet) {
			wxLogMessage(wxT("Save operation complete."));
		} else {
			tqslTrace("MyFrame::BackupConfig", "Save operation complete.");
		}
	}
	catch(TQSLException& x) {
		if (quiet) {
			wxString errmsg = wxString::Format(wxT("Error performing automatic backup: %hs"), x.what());
			wxMessageBox(errmsg, wxT("Backup Error"), wxOK|wxICON_EXCLAMATION);
		} else {
			wxLogError(wxT("Backup operation failed: %hs"), x.what());
		}
	}
}

void
MyFrame::OnSaveConfig(wxCommandEvent& WXUNUSED(event)) {
	tqslTrace("MyFrame::OnSaveConfig");
	try {
		wxString file_default = wxT("tqslconfig.tbk");
		wxString filename = wxFileSelector(wxT("Enter file to save to"), wxT(""),
			file_default, wxT(".tbk"), wxT("Configuration files (*.tbk)|*.tbk|All files (*.*)|*.*"),
			wxFD_SAVE|wxFD_OVERWRITE_PROMPT, this);
		if (filename == wxT(""))
			return;

		BackupConfig(filename, false);
	}
	catch(TQSLException& x) {
		wxLogError(wxT("Backup operation failed: %hs"), x.what());
	}
}


void
restore_user_cert(TQSLConfig* loader) {
	get_certlist(loader->callSign.c_str(), loader->dxcc, true, true, true);
	for (int i = 0; i < ncerts; i++) {
		long serial;
		int dxcc;
		int keyonly;
		check_tqsl_error(tqsl_getCertificateKeyOnly(certlist[i], &keyonly));
		check_tqsl_error(tqsl_getCertificateDXCCEntity(certlist[i], &dxcc));
		if (!keyonly) {
			check_tqsl_error(tqsl_getCertificateSerial(certlist[i], &serial));
			if (serial == loader->serial && dxcc == loader->dxcc) {
				return;			// This certificate is already installed.
			}
		} else {
			// See if the keyonly cert is the one we're trying to load
			char buf[8192];
			check_tqsl_error(tqsl_getKeyEncoded(certlist[i], buf, sizeof buf));
			if (!strcmp(buf, loader->privateKey.ToUTF8())) {
				return;			// Already installed
			}
		}
	}

	// There is no certificate matching this callsign/entity/serial.
	wxLogMessage(wxT("\tRestoring callsign certificate for %hs"), loader->callSign.c_str());
	wxSafeYield(frame);
	check_tqsl_error(tqsl_importKeyPairEncoded(loader->callSign.c_str(), "user", loader->privateKey.ToUTF8(), loader->signedCert.ToUTF8()));
}

void
restore_root_cert(TQSLConfig* loader) {
	check_tqsl_error(tqsl_importKeyPairEncoded(NULL, "root", NULL, loader->signedCert.ToUTF8()));
}

void
restore_ca_cert(TQSLConfig* loader) {
	check_tqsl_error(tqsl_importKeyPairEncoded(NULL, "authorities", NULL, loader->signedCert.ToUTF8()));
}

void
TQSLConfig::xml_restore_start(void *data, const XML_Char *name, const XML_Char **atts) {
	TQSLConfig* loader = reinterpret_cast<TQSLConfig *> (data);
	int i;

	loader->elementBody = wxT("");
	if (strcmp(name, "UserCert") == 0) {
		for (int i = 0; atts[i]; i+=2) {
			if (strcmp(atts[i], "CallSign") == 0) {
				loader->callSign = atts[i + 1];
			} else if (strcmp(atts[i], "serial") == 0) {
				if (strlen(atts[i+1]) == 0) {
					loader->serial = 0;
				} else {
					loader->serial =  strtol(atts[i+1], NULL, 10);
				}
			} else if (strcmp(atts[i], "dxcc") == 0) {
				if (strlen(atts[i+1]) == 0) {
					loader->dxcc = 0;
				} else {
					loader->dxcc =  strtol(atts[i+1], NULL, 10);
				}
			}
		}
		loader->privateKey = wxT("");
		loader->signedCert = wxT("");
	} else if (strcmp(name, "TQSLSettings") == 0) {
		wxLogMessage(wxT("Restoring Preferences"));
		wxSafeYield(frame);
		loader->config = new wxConfig(wxT("tqslapp"));
	} else if (strcmp(name, "Setting") == 0) {
		wxString sname;
		wxString sgroup;
		wxString stype;
		wxString svalue;
		for (i = 0; atts[i]; i+=2) {
			if (strcmp(atts[i], "name") == 0) {
				sname = wxString::FromUTF8(atts[i+1]);
			} else if (strcmp(atts[i], "group") == 0) {
				sgroup = wxString::FromUTF8(atts[i+1]);
			} else if (strcmp(atts[i], "Type") == 0) {
				stype = wxString::FromUTF8(atts[i+1]);
			} else if (strcmp(atts[i], "Value") == 0) {
				svalue = wxString::FromUTF8(atts[i+1]);
			}
		}
		loader->config->SetPath(sgroup);
		if (stype == wxT("String")) {
			svalue.Replace(wxT("&lt;"), wxT("<"), true);
			svalue.Replace(wxT("&gt;"), wxT(">"), true);
			svalue.Replace(wxT("&amp;"), wxT("&"), true);
			if (sname == wxT("BackupFolder") && !svalue.IsEmpty()) {
				// If it's the backup directory, don't restore it if the
				// referenced directory doesn't exist.
				struct stat s;
#ifdef _WIN32
#define lstat stat
#define S_ISDIR(mode)	(((mode) & S_IFMT) == _S_IFDIR)
#endif

				if (lstat(tqslName(svalue), &s) == 0) {		// Does it exist?
					if (S_ISDIR(s.st_mode)) {		// And is it a directory?
						loader->config->Write(sname, svalue); // OK to use it.
					}
                		}
			} else {
				loader->config->Write(sname, svalue);
			}
		} else if (stype == wxT("Bool")) {
			bool bsw = (svalue == wxT("true"));
			loader->config->Write(sname, bsw);
		} else if (stype == wxT("Int")) {
			long lval = strtol(svalue.ToUTF8(), NULL, 10);
			loader->config->Write(sname, lval);
		} else if (stype == wxT("Float")) {
			double dval = strtod(svalue.ToUTF8(), NULL);
			loader->config->Write(sname, dval);
		}
	} else if (strcmp(name, "Locations") == 0) {
		wxLogMessage(wxT("Restoring Station Locations"));
		wxSafeYield(frame);
		loader->locstring = wxT("<StationDataFile>\n");
	} else if (strcmp(name, "Location") == 0) {
		for (i = 0; atts[i]; i+=2) {
			wxString attname = wxString::FromUTF8(atts[i+1]);
			if (strcmp(atts[i], "name") == 0) {
				loader->locstring += wxT("<StationData name=\"") + urlEncode(attname) + wxT("\">\n");
				break;
			}
		}
		for (i = 0; atts[i]; i+=2) {
			wxString attname = wxString::FromUTF8(atts[i+1]);
			if (strcmp(atts[i], "name") != 0) {
				loader->locstring += wxT("<") + wxString::FromUTF8(atts[i]) + wxT(">") +
					urlEncode(attname) + wxT("</") + wxString::FromUTF8(atts[i]) + wxT(">\n");
			}
		}
	} else if (strcmp(name, "DupeDb") == 0) {
		wxLogMessage(wxT("Restoring QSO records"));
		wxSafeYield(frame);
		check_tqsl_error(tqsl_beginConverter(&loader->conv));
	} else if (strcmp(name, "Dupe") == 0) {
		for (i = 0; atts[i]; i+=2) {
			if (strcmp(atts[i], "key") == 0) {
				int status = tqsl_putDuplicateRecord(loader->conv,  atts[i+1], "D", strlen(atts[i+1]));
				if (status >= 0) check_tqsl_error(status);
			}
			if ((loader->dupes++ % 100000) == 0)
				wxSafeYield(frame);
		}
	}
}

void
TQSLConfig::xml_restore_end(void *data, const XML_Char *name) {
	TQSLConfig* loader = reinterpret_cast<TQSLConfig *> (data);
	if (strcmp(name, "SignedCert") == 0) {
		loader->signedCert = loader->elementBody.Trim(false);
	} else if (strcmp(name, "PrivateKey") == 0) {
		loader->privateKey = loader->elementBody.Trim(false);
	} else if (strcmp(name, "RootCert") == 0) {
		loader->signedCert = loader->elementBody.Trim(false);
		restore_root_cert(loader);
	} else if (strcmp(name, "CACert") == 0) {
		loader->signedCert = loader->elementBody.Trim(false);
		restore_ca_cert(loader);
	} else if (strcmp(name, "UserCert") == 0) {
		restore_user_cert(loader);
	} else if (strcmp(name, "Location") == 0) {
		loader->locstring += wxT("</StationData>\n");
	} else if (strcmp(name, "Locations") == 0) {
		loader->locstring += wxT("</StationDataFile>\n");
		if (tqsl_mergeStationLocations(loader->locstring.ToUTF8()) != 0) {
			wxLogError(wxT("\tError importing station locations: %hs"), tqsl_getErrorString());
		}
	} else if (strcmp(name, "TQSLSettings") == 0) {
		loader->config->Flush(false);
	} else if (strcmp(name, "DupeDb") == 0) {
		check_tqsl_error(tqsl_converterCommit(loader->conv));
		check_tqsl_error(tqsl_endConverter(&loader->conv));
	}
	loader->elementBody = wxT("");
}

void
TQSLConfig::xml_location_start(void *data, const XML_Char *name, const XML_Char **atts) {
	TQSLConfig* parser = reinterpret_cast<TQSLConfig *> (data);

	if (strcmp(name, "StationDataFile") == 0)
		return;
	if (strcmp(name, "StationData") == 0) {
		wxString locname = wxString::FromUTF8(atts[1]);
		urlEncode(locname);
		gzprintf(*parser->outstr, "<Location name=\"%s\"", (const char *)locname.ToUTF8());
	}
}
void
TQSLConfig::xml_location_end(void *data, const XML_Char *name) {
	TQSLConfig* parser = reinterpret_cast<TQSLConfig *> (data);
	if (strcmp(name, "StationDataFile") == 0)
		return;
	if (strcmp(name, "StationData") == 0) {
		gzprintf(*parser->outstr , " />\n");
		return;
	}
	// Anything else is a station attribute. Add it to the definition.
	parser->elementBody.Trim(false);
	parser->elementBody.Trim(true);
	urlEncode(parser->elementBody);
	gzprintf(*parser->outstr,  " %s=\"%s\"", name, (const char *)parser->elementBody.ToUTF8());
	parser->elementBody = wxT("");
}

void
TQSLConfig::xml_text(void *data, const XML_Char *text, int len) {
	TQSLConfig* loader = reinterpret_cast<TQSLConfig *>(data);
	char buf[512];
	memcpy(buf, text, len);
	buf[len] = '\0';
	loader->elementBody += wxString::FromUTF8(buf);
}

void
TQSLConfig::RestoreConfig(const gzFile& in) {
	tqslTrace("TQSLConfig::RestoreConfig");
	XML_Parser xp = XML_ParserCreate(0);
	XML_SetUserData(xp, reinterpret_cast<void *>(this));
	XML_SetStartElementHandler(xp, &TQSLConfig::xml_restore_start);
	XML_SetEndElementHandler(xp, &TQSLConfig::xml_restore_end);
	XML_SetCharacterDataHandler(xp, &TQSLConfig::xml_text);

	char buf[4096];
	wxBusyCursor wait;
	wxLogMessage(wxT("Restoring Callsign Certificates"));
	wxSafeYield(frame);
	int rcount = 0;
	do {
		rcount = gzread(in, buf, sizeof(buf));
		if (rcount > 0) {
			if (XML_Parse(xp, buf, rcount, 0) == 0) {
				wxLogError(wxT("Error parsing saved configuration file: %hs"), XML_ErrorString(XML_GetErrorCode(xp)));
				XML_ParserFree(xp);
				gzclose(in);
				return;
			}
		}
	} while (rcount > 0);
	if (!gzeof(in)) {
		int gerr;
		wxLogError(wxT("Error parsing saved configuration file: %hs"), gzerror(in, &gerr));
		XML_ParserFree(xp);
		return;
	}
	if (XML_Parse(xp, "", 0, 1) == 0) {
		wxLogError(wxT("Error parsing saved configuration file: %hs"), XML_ErrorString(XML_GetErrorCode(xp)));
		XML_ParserFree(xp);
		return;
	}
	wxLogMessage(wxT("Restore Complete."));
}

void
TQSLConfig::ParseLocations(gzFile* out, const tQSL_StationDataEnc loc) {
	tqslTrace("TQSL::ParseLocations", "loc=%s", loc);
	XML_Parser xp = XML_ParserCreate(0);
	XML_SetUserData(xp, reinterpret_cast<void *>(this));
	XML_SetStartElementHandler(xp, &TQSLConfig::xml_location_start);
	XML_SetEndElementHandler(xp, &TQSLConfig::xml_location_end);
	XML_SetCharacterDataHandler(xp, &TQSLConfig::xml_text);
	outstr = out;

	if (XML_Parse(xp, loc, strlen(loc), 1) == 0) {
		wxLogError(wxT("Error parsing station location file: %hs"), XML_ErrorString(XML_GetErrorCode(xp)));
		XML_ParserFree(xp);
		return;
	}
}

void
MyFrame::OnLoadConfig(wxCommandEvent& WXUNUSED(event)) {
	tqslTrace("MyFrame::OnLoadConfig");
	wxString filename = wxFileSelector(wxT("Select saved configuration file"), wxT(""),
					   wxT("tqslconfig.tbk"), wxT("tbk"), wxT("Saved configuration files (*.tbk)|*.tbk"),
					   wxFD_OPEN|wxFD_FILE_MUST_EXIST);
	if (filename == wxT(""))
		return;

	gzFile in = 0;
	try {
		in = gzopen(tqslName(filename), "rb");
		if (!in) {
			wxLogError(wxT("Error opening save file %s: %hs"), filename.c_str(), strerror(errno));
			return;
		}

		TQSLConfig* loader = new TQSLConfig();
		loader->RestoreConfig(in);
		cert_tree->Build(CERTLIST_FLAGS);
		loc_tree->Build();
		LocTreeReset();
		CertTreeReset();
		gzclose(in);
	}
	catch(TQSLException& x) {
		wxLogError(wxT("Restore operation failed: %hs"), x.what());
		gzclose(in);
	}
}

QSLApp::QSLApp() : wxApp() {
#ifdef __WXMAC__	// Tell wx to put these items on the proper menu
	wxApp::s_macAboutMenuItemId = long(tm_h_about);
	wxApp::s_macPreferencesMenuItemId = long(tm_f_preferences);
	wxApp::s_macExitMenuItemId = long(tm_f_exit);
#endif

	wxConfigBase::Set(new wxConfig(wxT("tqslapp")));
}

/*
wxLog *
QSLApp::CreateLogTarget() {
cerr << "called" << endl;
	MyFrame *mf = (MyFrame *)GetTopWindow();
	if (mf)
		return new LogList(mf);
	return 0;
}
*/

MyFrame *
QSLApp::GUIinit(bool checkUpdates, bool quiet) {
	tqslTrace("QSLApp::GUIinit", "checkUpdates=%d", checkUpdates);
	int x, y, w, h;
	wxConfig *config = reinterpret_cast<wxConfig *>(wxConfig::Get());
	config->Read(wxT("MainWindowX"), &x, 50);
	config->Read(wxT("MainWindowY"), &y, 50);
	config->Read(wxT("MainWindowWidth"), &w, 800);
	config->Read(wxT("MainWindowHeight"), &h, 600);

	if (w < MAIN_WINDOW_MIN_WIDTH) w = MAIN_WINDOW_MIN_WIDTH;
	if (h < MAIN_WINDOW_MIN_HEIGHT) w = MAIN_WINDOW_MIN_HEIGHT;

	frame = new MyFrame(wxT("TQSL"), x, y, w, h, checkUpdates, quiet);
	frame->SetMinSize(wxSize(MAIN_WINDOW_MIN_WIDTH, MAIN_WINDOW_MIN_HEIGHT));
	if (checkUpdates)
		frame->FirstTime();
	frame->Show(!quiet);
	SetTopWindow(frame);

	return frame;
}

// Override OnRun so we can have a last-chance exception handler
// in case something doesn't handle an error.
int
QSLApp::OnRun() {
	tqslTrace("QSLApp::OnRun");
	try {
		if (m_exitOnFrameDelete == Later)
			m_exitOnFrameDelete = Yes;
		return MainLoop();
	}
	catch(TQSLException& x) {
		string msg = x.what();
		tqslTrace("QSLApp::OnRun", "Last chance handler, string=%s", (const char *)msg.c_str());
		cerr << "An exception has occurred! " << msg << endl;
		wxLogError(wxT("%hs"), x.what());
		exitNow(TQSL_EXIT_TQSL_ERROR, false);
	}
	return 0;
}

bool
QSLApp::OnInit() {
	frame = 0;
	bool quiet = false;

	int major, minor;
	if (tqsl_getConfigVersion(&major, &minor)) {
		wxMessageBox(wxString::FromUTF8(tqsl_getErrorString()), wxT("Error"), wxOK);
		exitNow(TQSL_EXIT_TQSL_ERROR, quiet);
	}
	wxFileSystem::AddHandler(new tqslInternetFSHandler());

	//short circuit if no arguments

	if (argc <= 1) {
		GUIinit(true, quiet);
		return true;
	}

	tQSL_Location loc = 0;
	wxString locname;
	bool suppressdate = false;
	int action = TQSL_ACTION_UNSPEC;
	bool upload = false;
	char *password = NULL;
	wxString infile(wxT(""));
	wxString outfile(wxT(""));
	wxString importfile(wxT(""));
	wxString diagfile(wxT(""));

	wxCmdLineParser parser;

	static const wxCmdLineEntryDesc cmdLineDesc[] = {
	        { wxCMD_LINE_OPTION, "a", "action",	"Specify dialog action - abort, all, compliant or ask" },
	        { wxCMD_LINE_OPTION, "b", "begindate", "Specify start date for QSOs to sign" },
	        { wxCMD_LINE_OPTION, "e", "enddate",	"Specify end date for QSOs to sign" },
	        { wxCMD_LINE_SWITCH, "d", "nodate",	"Suppress date range dialog" },
	        { wxCMD_LINE_OPTION, "i", "import",	"Import a certificate file (.p12 or .tq6)" },
	        { wxCMD_LINE_OPTION, "l", "location",	"Selects Station Location" },
	        { wxCMD_LINE_SWITCH, "s", "editlocation", "Edit (if used with -l) or create Station Location" },
	        { wxCMD_LINE_OPTION, "o", "output",	"Output file name (defaults to input name minus extension plus .tq8" },
	        { wxCMD_LINE_SWITCH, "u", "upload",	"Upload after signing instead of saving" },
	        { wxCMD_LINE_SWITCH, "x", "batch",	"Exit after processing log (otherwise start normally)" },
	        { wxCMD_LINE_OPTION, "p", "password",	"Password for the signing key" },
	        { wxCMD_LINE_SWITCH, "q", "quiet",	"Quiet Mode - same behavior as -x" },
	        { wxCMD_LINE_OPTION, "t", "diagnose",	"File name for diagnostic tracking log" },
	        { wxCMD_LINE_SWITCH, "v", "version",  "Display the version information and exit" },
	        { wxCMD_LINE_SWITCH, "n", "updates",	"Check for updates to tqsl and the configuration file" },
	        { wxCMD_LINE_SWITCH, "h", "help",	"Display command line help", wxCMD_LINE_VAL_NONE, wxCMD_LINE_OPTION_HELP },
	        { wxCMD_LINE_PARAM,  NULL,     NULL,		"Input ADIF or Cabrillo log file to sign", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
	        { wxCMD_LINE_NONE }
	};

	// Lowercase command options
	origCommandLine = argv[0];
	for (int i = 1; i < argc; i++) {
		origCommandLine += wxT(" ");
		origCommandLine += argv[i];
		if (!argv[i].empty() && (argv[i][0] == wxT('-') || argv[i][0] == wxT('/')))
			if (wxIsalpha(argv[i][1]) && wxIsupper(argv[i][1]))
				argv[i][1] = wxTolower(argv[i][1]);
	}

	parser.SetCmdLine(argc, argv);
	parser.SetDesc(cmdLineDesc);
	// only allow "-" for options, otherwise "/path/something.adif"
	// is parsed as "-path"
	//parser.SetSwitchChars(wxT("-")); //by default, this is '-' on Unix, or '-' or '/' on Windows. We should respect the Win32 conventions, but allow the cross-platform Unix one for cross-plat loggers
	int parseStatus = parser.Parse(true);
	if (parseStatus == -1) {	// said "-h"
		return false;
	}
	// Always display TQSL version
	if ((!parser.Found(wxT("n"))) || parser.Found(wxT("v"))) {
		cerr << "TQSL Version " VERSION " " BUILD "\n";
	}
	if (parseStatus != 0)  {
		exitNow(TQSL_EXIT_COMMAND_ERROR, quiet);
	}

	// version already displayed - just exit
	if (parser.Found(wxT("v"))) {
		return false;
	}

	if (parser.Found(wxT("x")) || parser.Found(wxT("q"))) {
		quiet = true;
		wxLog::SetActiveTarget(new LogStderr());
	}

	if (parser.Found(wxT("t"), &diagfile)) {
		diagFile = fopen(tqslName(diagfile), "wb");
		if (!diagFile) {
			cerr << "Error opening diagnostic log " << tqslName(diagfile) << ": " << strerror(errno) << endl;
		} else {
			wxString about = getAbout();
			fprintf(diagFile, "TQSL Diagnostics\n%s\n\n", (const char *)about.ToUTF8());
			fprintf(diagFile, "Command Line: %s\n", (const char *)origCommandLine.ToUTF8());
			tqsl_init();
			fprintf(diagFile, "Working Directory: %s\n", tQSL_BaseDir);
		}
	}

	tqsl_init();	// Init tqsllib
	// check for logical command switches
	if (parser.Found(wxT("o")) && parser.Found(wxT("u"))) {
		cerr << "Option -o cannot be combined with -u" << endl;
		exitNow(TQSL_EXIT_COMMAND_ERROR, quiet);
	}
	if ((parser.Found(wxT("o")) || parser.Found(wxT("u"))) && parser.Found(wxT("s"))) {
		cerr << "Option -s cannot be combined with -u or -o" << endl;
		exitNow(TQSL_EXIT_COMMAND_ERROR, quiet);
	}
	if (parser.Found(wxT("s")) && parser.GetParamCount() > 0) {
		cerr << "Option -s cannot be combined with an input file" << endl;
		exitNow(TQSL_EXIT_COMMAND_ERROR, quiet);
	}

	// Request to check for new versions of tqsl/config/certs
	if (parser.Found(wxT("n"))) {
		if (parser.Found(wxT("i")) || parser.Found(wxT("o")) ||
		    parser.Found(wxT("s")) || parser.Found(wxT("u"))) {
			cerr << "Option -n cannot be combined with any other options" << endl;
			exitNow(TQSL_EXIT_COMMAND_ERROR, quiet);
		}
		frame = GUIinit(false, true);
		frame->Show(false);
		// Check for updates then bail out.
		wxLog::SetActiveTarget(new LogStderr());
		frame->DoUpdateCheck(false, true);
		return(false);
	}

	frame =GUIinit(!quiet, quiet);
	if (quiet) {
		wxLog::SetActiveTarget(new LogStderr());
		frame->Show(false);
	}
	if (parser.Found(wxT("i"), &importfile)) {
		importfile.Trim(true).Trim(false);
		notifyData nd;
		if (tqsl_importTQSLFile(tqslName(importfile), notifyImport, &nd)) {
			wxLogError(wxT("%hs"), tqsl_getErrorString());
		} else {
			wxLogMessage(nd.Message());
			if (tQSL_ImportCall[0] != '\0') {
				get_certlist(tQSL_ImportCall, 0, false, true, true);	// Get any superceded ones for this call
				for (int i = 0; i < ncerts; i++) {
					int sup;
					if (tqsl_isCertificateSuperceded(certlist[i], &sup) == 0) {
						if (sup) {
							tqsl_deleteCertificate(certlist[i]);	// and delete them.
						}
					}
				}
			}
			frame->cert_tree->Build(CERTLIST_FLAGS);
			wxString call = wxString::FromUTF8(tQSL_ImportCall);
			wxString pending = wxConfig::Get()->Read(wxT("RequestPending"));
			pending.Replace(call, wxT(""), true);
			wxString rest;
			while (pending.StartsWith(wxT(","), &rest))
				pending = rest;
			while (pending.EndsWith(wxT(","), &rest))
				pending = rest;
			wxConfig::Get()->Write(wxT("RequestPending"), pending);
		}
		return(true);
	}

	if (parser.Found(wxT("l"), &locname)) {
		locname.Trim(true);			// clean up whitespace
		locname.Trim(false);
		tqsl_endStationLocationCapture(&loc);
		if (tqsl_getStationLocation(&loc, locname.ToUTF8())) {
			if (quiet) {
				wxLogError(wxT("%hs"), tqsl_getErrorString());
				exitNow(TQSL_EXIT_COMMAND_ERROR, quiet);
			} else {
				wxMessageBox(wxString::FromUTF8(tqsl_getErrorString()), ErrorTitle, wxOK|wxCENTRE, frame);
				return false;
			}
		}
	}
	wxString pwd;
	if (parser.Found(wxT("p"), &pwd)) {
		password = strdup(pwd.ToUTF8());
		utf8_to_ucs2(password, unipwd, sizeof unipwd);
	}
	parser.Found(wxT("o"), &outfile);
	if (parser.Found(wxT("d"))) {
		suppressdate = true;
	}
	wxString start = wxT("");
	wxString end = wxT("");
	tQSL_Date* startdate = NULL;
	tQSL_Date* enddate = NULL;
	tQSL_Date s, e;
	if (parser.Found(wxT("b"), &start)) {
		if (start.Trim() == wxT(""))
			startdate = NULL;
		else if (tqsl_initDate(&s, start.ToUTF8()) || !tqsl_isDateValid(&s)) {
			if (quiet) {
				wxLogError(wxT("Start date of %s is invalid"), start.c_str());
				exitNow(TQSL_EXIT_COMMAND_ERROR, quiet);
			} else {
				wxMessageBox(wxString::Format(wxT("Start date of %s is invalid"), start.c_str()), ErrorTitle, wxOK|wxCENTRE, frame);
				return false;
			}
		}
		startdate = &s;
	}
	if (parser.Found(wxT("e"), &end)) {
		if (end.Trim() == wxT(""))
			enddate = NULL;
		else if (tqsl_initDate(&e, end.ToUTF8()) || !tqsl_isDateValid(&e)) {
			if (quiet) {
				wxLogError(wxT("End date of %s is invalid"), end.c_str());
				exitNow(TQSL_EXIT_COMMAND_ERROR, quiet);
			} else {
				wxMessageBox(wxString::Format(wxT("End date of %s is invalid"), end.c_str()), ErrorTitle, wxOK|wxCENTRE, frame);
				return false;
			}
		}
		enddate = &e;
	}

	wxString act;
	if (parser.Found(wxT("a"), &act)) {
		if (!act.CmpNoCase(wxT("abort"))) {
			action = TQSL_ACTION_ABORT;
		} else if (!act.CmpNoCase(wxT("compliant"))) {
			action = TQSL_ACTION_NEW;
		} else if (!act.CmpNoCase(wxT("all"))) {
			action = TQSL_ACTION_ALL;
		} else if (!act.CmpNoCase(wxT("ask"))) {
			action = TQSL_ACTION_ASK;
		} else {
			char tmp[100];
			strncpy(tmp, (const char *)act.ToUTF8(), sizeof tmp);
			tmp[sizeof tmp -1] = '\0';
			if (quiet)
				wxLogMessage(wxT("The -a parameter %hs is not recognized"), tmp);
			else
				cerr << "The action parameter " << tmp << " is not recognized" << endl;
			exitNow(TQSL_EXIT_COMMAND_ERROR, quiet);
		}
	}
	if (parser.Found(wxT("u"))) {
		upload = true;
	}
	if (parser.Found(wxT("s"))) {
		// Add/Edit station location
		if (loc == 0) {
			if (tqsl_initStationLocationCapture(&loc)) {
				wxLogError(wxT("%hs"), tqsl_getErrorString());
			}
			AddEditStationLocation(loc, true);
		} else {
			AddEditStationLocation(loc, false, wxT("Edit Station Location"));
		}
		return false;
	}
	if (parser.GetParamCount() > 0) {
		infile = parser.GetParam(0);
	}
	// We need a logfile, else there's nothing to do.
	if (wxIsEmpty(infile)) {	// Nothing to sign
		if (diagFile)		// Unless there's just a trace log
			return true;	// in which case we let it open.
		wxLogError(wxT("No logfile to sign!"));
		if (quiet)
			exitNow(TQSL_EXIT_COMMAND_ERROR, quiet);
		return false;
	}
	if (loc == 0) {
		try {
			loc = frame->SelectStationLocation(wxT("Select Station Location for Signing"));
		}
		catch(TQSLException& x) {
			wxLogError(wxT("%hs"), x.what());
			if (quiet)
				exitNow(TQSL_EXIT_CANCEL, quiet);
		}
	}
	// If no location specified and not chosen, can't sign. Exit.
	if (loc == 0) {
		if (quiet)
			exitNow(TQSL_EXIT_CANCEL, quiet);
		return false;
	}
	wxString path, name, ext;
	if (!wxIsEmpty(outfile)) {
		path = outfile;
	} else {
		wxSplitPath(infile, &path, &name, &ext);
		if (!wxIsEmpty(path))
			path += wxT("/");
		path += name + wxT(".tq8");
	}
	if (upload) {
		try {
			int val = frame->UploadLogFile(loc, infile, true, suppressdate, startdate, enddate, action, password);
			if (quiet)
				exitNow(val, quiet);
			else
				return true;	// Run the GUI
		} catch(TQSLException& x) {
			wxString s;
			wxString err = wxString::FromUTF8(x.what());
			if (err.Find(infile) == wxNOT_FOUND) {
				if (!infile.empty())
                                	s = infile + wxT(": ");
                	}
			s += err;
			wxLogError(wxT("%s"), (const char *)s.c_str());
			if (quiet)
				exitNow(TQSL_EXIT_LIB_ERROR, quiet);
			else
				return true;
		}
	} else {
		try {
			int val = frame->ConvertLogFile(loc, infile, path, true, suppressdate, startdate, enddate, action, password);
			if (quiet)
				exitNow(val, quiet);
			else
				return true;
		} catch(TQSLException& x) {
			wxString s;
			wxString err = wxString::FromUTF8(x.what());
			if (err.Find(infile) == wxNOT_FOUND) {
				if (infile != wxT(""))
					s = infile + wxT(": ");
			}
			s += err;
			wxLogError(wxT("%s"), (const char *)s.c_str());
			if (quiet)
				exitNow(TQSL_EXIT_LIB_ERROR, quiet);
			else
				return true;
		}
	}
	if (quiet)
		exitNow(TQSL_EXIT_SUCCESS, quiet);
	return true;
}


void MyFrame::FirstTime(void) {
	tqslTrace("MyFrame::FirstTime");
	if (wxConfig::Get()->Read(wxT("HasRun")) == wxT("")) {
		wxConfig::Get()->Write(wxT("HasRun"), wxT("yes"));
		DisplayHelp();
		wxMessageBox(wxT("Please review the introductory documentation before using this program."),
			wxT("Notice"), wxOK, this);
	}
	int ncerts = cert_tree->Build(CERTLIST_FLAGS);
	CertTreeReset();
	if (ncerts == 0 && wxMessageBox(wxT("You have no callsign certificate installed on this computer with which to sign log submissions.\n")
		wxT("Would you like to request a callsign certificate now?"), wxT("Alert"), wxYES_NO, this) == wxYES) {
		wxCommandEvent e;
		CRQWizard(e);
	}
	wxString pending = wxConfig::Get()->Read(wxT("RequestPending"));
	wxStringTokenizer tkz(pending, wxT(","));
	while (tkz.HasMoreTokens()) {
		wxString pend = tkz.GetNextToken();
		bool found = false;
		tQSL_Cert *certs;
		int ncerts = 0;
		if (!tqsl_selectCertificates(&certs, &ncerts, pend.ToUTF8(), 0, 0, 0, TQSL_SELECT_CERT_WITHKEYS)) {
			for (int i = 0; i < ncerts; i++) {
				int keyonly;
				if (!tqsl_getCertificateKeyOnly(certs[i], &keyonly)) {
					if (!found && keyonly)
						found = true;
				}
				tqsl_freeCertificate(certs[i]);
			}
			tqsl_freeStationDataEnc(reinterpret_cast<char *>(certs));
		}

		if (!found) {
			// Remove this call from the list of pending certificate requests
			wxString p = wxConfig::Get()->Read(wxT("RequestPending"));
			p.Replace(pend, wxT(""), true);
			wxString rest;
			while (p.StartsWith(wxT(","), &rest))
				p = rest;
			while (p.EndsWith(wxT(","), &rest))
				p = rest;
			wxConfig::Get()->Write(wxT("RequestPending"), p);
		}
	}

	if (ncerts > 0) {
		TQ_WXCOOKIE cookie;
		wxTreeItemId it = cert_tree->GetFirstChild(cert_tree->GetRootItem(), cookie);
		while (it.IsOk()) {
			if (cert_tree->GetItemText(it) == wxT("Test Certificate Authority")) {
				wxMessageBox(wxT("You must delete your beta-test certificates (the ones\n")
					wxT("listed under \"Test Certificate Authority\") to ensure proprer\n")
					wxT("operation of the TrustedQSL software."), wxT("Warning"), wxOK, this);
				break;
			}
			it = cert_tree->GetNextChild(cert_tree->GetRootItem(), cookie);
		}
	}
// Copy tqslcert preferences to tqsl unless already done.
	if (wxConfig::Get()->Read(wxT("PrefsMigrated")) == wxT("")) {
		wxConfig::Get()->Write(wxT("PrefsMigrated"), wxT("yes"));
		tqslTrace("MyFrame::FirstTime", "Migrating preferences from tqslcert");
		wxConfig* certconfig = new wxConfig(wxT("tqslcert"));

		wxString name, gname;
		long	context;
		wxString svalue;
		long	lvalue;
		bool	bvalue;
		double	dvalue;
		wxArrayString groupNames;

		groupNames.Add(wxT("/"));
		bool more = certconfig->GetFirstGroup(gname, context);
		while (more) {
			groupNames.Add(wxT("/") + gname);
			more = certconfig->GetNextGroup(gname, context);
		}

		for (unsigned i = 0; i < groupNames.GetCount(); i++) {
			certconfig->SetPath(groupNames[i]);
			wxConfig::Get()->SetPath(groupNames[i]);
			more = certconfig->GetFirstEntry(name, context);
			while (more) {
				wxConfigBase::EntryType etype = certconfig->GetEntryType(name);
				switch (etype) {
                                        case wxConfigBase::Type_Unknown:
                                        case wxConfigBase::Type_String:
						certconfig->Read(name, &svalue);
						wxConfig::Get()->Write(name, svalue);
						break;
                                        case wxConfigBase::Type_Boolean:
						certconfig->Read(name, &bvalue);
						wxConfig::Get()->Write(name, bvalue);
						break;
                                        case wxConfigBase::Type_Integer:
						certconfig->Read(name, &lvalue);
						wxConfig::Get()->Write(name, lvalue);
						break;
                                        case wxConfigBase::Type_Float:
						certconfig->Read(name, &dvalue);
						wxConfig::Get()->Write(name, dvalue);
						break;
				}
				more = certconfig->GetNextEntry(name, context);
			}
		}
		delete certconfig;
		wxConfig::Get()->SetPath(wxT("/"));
		wxConfig::Get()->Flush();
	}
	// Find and report conflicting mode maps
	init_modes();
	wxConfig *config = reinterpret_cast<wxConfig *>(wxConfig::Get());
	if (config->Read(wxT("AutoUpdateCheck"), true)) {
		DoUpdateCheck(true, false);
	}
	return;
}

wxMenu *
makeCertificateMenu(bool enable, bool keyonly) {
	tqslTrace("makeCertificateMenu", "enable=%d, keyonly=%d", enable, keyonly);
	wxMenu *c_menu = new wxMenu;
	c_menu->Append(tc_c_Properties, wxT("Display Callsign Certificate &Properties"));
	c_menu->Enable(tc_c_Properties, enable);
	c_menu->AppendSeparator();
	c_menu->Append(tc_c_Load, wxT("&Load Callsign Certificate from File"));
	c_menu->Append(tc_c_Export, wxT("&Save Callsign Certificate to File..."));
	c_menu->Enable(tc_c_Export, enable);
	if (!keyonly) {
		c_menu->AppendSeparator();
		c_menu->Append(tc_c_New, wxT("Request &New Callsign Certificate..."));
		c_menu->Append(tc_c_Renew, wxT("&Renew Callsign Certificate"));
		c_menu->Enable(tc_c_Renew, enable);
	} else {
		c_menu->AppendSeparator();
	}
	c_menu->Append(tc_c_Delete, wxT("&Delete Callsign Certificate"));
	c_menu->Enable(tc_c_Delete, enable);
	return c_menu;
}

wxMenu *
makeLocationMenu(bool enable) {
	tqslTrace("makeLocationMenu", "enable=%d", enable);
	wxMenu *loc_menu = new wxMenu;
	loc_menu->Append(tl_c_Properties, wxT("&Properties"));
	loc_menu->Enable(tl_c_Properties, enable);
	stn_menu->Enable(tm_s_Properties, enable);
	loc_menu->Append(tl_c_Edit, wxT("&Edit"));
	loc_menu->Enable(tl_c_Edit, enable);
	loc_menu->Append(tl_c_Delete, wxT("&Delete"));
	loc_menu->Enable(tl_c_Delete, enable);
	return loc_menu;
}

/////////// Frame /////////////

void MyFrame::OnLoadCertificateFile(wxCommandEvent& WXUNUSED(event)) {
	tqslTrace("MyFrame::OnLoadCertificateFile");
	LoadCertWiz lcw(this, help, wxT("Load Certificate File"));
	lcw.RunWizard();
	if (tQSL_ImportCall[0] != '\0') {			// If a user cert was imported
		get_certlist(tQSL_ImportCall, 0, false, true, true);	// Get any superceded ones for this call
		for (int i = 0; i < ncerts; i++) {
			int sup;
			if (tqsl_isCertificateSuperceded(certlist[i], &sup) == 0) {
				if (sup) {
					tqsl_deleteCertificate(certlist[i]);	// and delete them.
				}
			}
		}
	}
	cert_tree->Build(CERTLIST_FLAGS);
	CertTreeReset();
}

void MyFrame::CRQWizardRenew(wxCommandEvent& event) {
	tqslTrace("MyFrame::CRQWizardRenew");
	CertTreeItemData *data = reinterpret_cast<CertTreeItemData *>(cert_tree->GetItemData(cert_tree->GetSelection()));
	req = 0;
	tQSL_Cert cert;
	wxString callSign, name, address1, address2, city, state, postalCode,
		country, emailAddress;
	if (data != NULL && (cert = data->getCert()) != 0) {	// Should be true
		char buf[256];
		req = new TQSL_CERT_REQ;
		if (!tqsl_getCertificateIssuerOrganization(cert, buf, sizeof buf))
			strncpy(req->providerName, buf, sizeof req->providerName);
		if (!tqsl_getCertificateIssuerOrganizationalUnit(cert, buf, sizeof buf))
			strncpy(req->providerUnit, buf, sizeof req->providerUnit);
		if (!tqsl_getCertificateCallSign(cert, buf, sizeof buf)) {
			callSign = wxString::FromUTF8(buf);
			strncpy(req->callSign, callSign.ToUTF8(), sizeof req->callSign);
		}
		if (!tqsl_getCertificateAROName(cert, buf, sizeof buf)) {
			name = wxString::FromUTF8(buf);
			strncpy(req->name, name.ToUTF8(), sizeof req->name);
		}
		tqsl_getCertificateDXCCEntity(cert, &(req->dxccEntity));
		tqsl_getCertificateQSONotBeforeDate(cert, &(req->qsoNotBefore));
		tqsl_getCertificateQSONotAfterDate(cert, &(req->qsoNotAfter));
		if (!tqsl_getCertificateEmailAddress(cert, buf, sizeof buf)) {
			emailAddress = wxString::FromUTF8(buf);
			strncpy(req->emailAddress, emailAddress.ToUTF8(), sizeof req->emailAddress);
		}
		if (!tqsl_getCertificateRequestAddress1(cert, buf, sizeof buf)) {
			address1 = wxString::FromUTF8(buf);
			strncpy(req->address1, address1.ToUTF8(), sizeof req->address1);
		}
		if (!tqsl_getCertificateRequestAddress2(cert, buf, sizeof buf)) {
			address2 = wxString::FromUTF8(buf);
			strncpy(req->address2, address2.ToUTF8(), sizeof req->address2);
		}
		if (!tqsl_getCertificateRequestCity(cert, buf, sizeof buf)) {
			city = wxString::FromUTF8(buf);
			strncpy(req->city, city.ToUTF8(), sizeof req->city);
		}
		if (!tqsl_getCertificateRequestState(cert, buf, sizeof buf)) {
			state = wxString::FromUTF8(buf);
			strncpy(req->state, state.ToUTF8(), sizeof req->state);
		}
		if (!tqsl_getCertificateRequestPostalCode(cert, buf, sizeof buf)) {
			postalCode = wxString::FromUTF8(buf);
			strncpy(req->postalCode, postalCode.ToUTF8(), sizeof req->postalCode);
		}
		if (!tqsl_getCertificateRequestCountry(cert, buf, sizeof buf)) {
			country = wxString::FromUTF8(buf);
			strncpy(req->country, country.ToUTF8(), sizeof req->country);
		}
	}
	CRQWizard(event);
	if (req)
		delete req;
	req = 0;
}

void MyFrame::CRQWizard(wxCommandEvent& event) {
	tqslTrace("MyFrame::CRQWizard");
	char renew = (req != 0) ? 1 : 0;
	tQSL_Cert cert = (renew ? (reinterpret_cast<CertTreeItemData *>(cert_tree->GetItemData(cert_tree->GetSelection()))->getCert()) : 0);
	CRQWiz wiz(req, cert, this, help, renew ? wxT("Renew a Callsign Certificate") : wxT("Request a new Callsign Certificate"));
	int retval = 0;
/*
	CRQ_ProviderPage *prov = new CRQ_ProviderPage(wiz, req);
	CRQ_IntroPage *intro = new CRQ_IntroPage(wiz, req);
	CRQ_NamePage *name = new CRQ_NamePage(wiz, req);
	CRQ_EmailPage *email = new CRQ_EmailPage(wiz, req);
	wxSize size = prov->GetSize();
	if (intro->GetSize().GetWidth() > size.GetWidth())
		size = intro->GetSize();
	if (name->GetSize().GetWidth() > size.GetWidth())
		size = name->GetSize();
	if (email->GetSize().GetWidth() > size.GetWidth())
		size = email->GetSize();
	CRQ_PasswordPage *pw = new CRQ_PasswordPage(wiz);
	CRQ_SignPage *sign = new CRQ_SignPage(wiz, size, &(prov->provider));
	wxWizardPageSimple::Chain(prov, intro);
	wxWizardPageSimple::Chain(intro, name);
	wxWizardPageSimple::Chain(name, email);
	wxWizardPageSimple::Chain(email, pw);
	if (renew)
		sign->cert = ;
	else
		wxWizardPageSimple::Chain(pw, sign);

	wiz.SetPageSize(size);

*/

	if (wiz.RunWizard()) {
		// Save or upload?
		wxString file = flattenCallSign(wiz.callsign) + wxT(".") + wxT(TQSL_CRQ_FILE_EXT);
		bool upload = false;
		if (wxMessageBox(wxT("Do you want to upload this certificate request to LoTW now?\n"
				     "You do not need an account on LoTW to do this."),
				wxT("Upload"), wxYES_NO|wxICON_QUESTION, this) == wxYES) {
			upload = true;
			// Save it in the working directory
#ifdef _WIN32
			file = wxString::FromUTF8(tQSL_BaseDir) + wxT("\\") + file;
#else
			file = wxString::FromUTF8(tQSL_BaseDir) + wxT("/") + file;
#endif
		} else {
			// Where to put it?
			file = wxFileSelector(wxT("Save request"), wxT(""), file, wxT(TQSL_CRQ_FILE_EXT),
				wxT("tQSL Cert Request files (*.") wxT(TQSL_CRQ_FILE_EXT) wxT(")|*.") wxT(TQSL_CRQ_FILE_EXT)
					wxT("|All files (") wxT(ALLFILESWILD) wxT(")|") wxT(ALLFILESWILD),
				wxFD_SAVE | wxFD_OVERWRITE_PROMPT);
			if (file.IsEmpty()) {
				wxLogMessage(wxT("Request cancelled"));
				return;
			}
		}
		TQSL_CERT_REQ req;
		strncpy(req.providerName, wiz.provider.organizationName, sizeof req.providerName);
		strncpy(req.providerUnit, wiz.provider.organizationalUnitName, sizeof req.providerUnit);
		strncpy(req.callSign, wiz.callsign.ToUTF8(), sizeof req.callSign);
		strncpy(req.name, wiz.name.ToUTF8(), sizeof req.name);
		strncpy(req.address1, wiz.addr1.ToUTF8(), sizeof req.address1);
		strncpy(req.address2, wiz.addr2.ToUTF8(), sizeof req.address2);
		strncpy(req.city, wiz.city.ToUTF8(), sizeof req.city);
		strncpy(req.state, wiz.state.ToUTF8(), sizeof req.state);
		strncpy(req.postalCode, wiz.zip.ToUTF8(), sizeof req.postalCode);
		if (wiz.country.IsEmpty())
			strncpy(req.country, "USA", sizeof req.country);
		else
			strncpy(req.country, wiz.country.ToUTF8(), sizeof req.country);
		strncpy(req.emailAddress, wiz.email.ToUTF8(), sizeof req.emailAddress);
		strncpy(req.password, wiz.password.ToUTF8(), sizeof req.password);
		req.dxccEntity = wiz.dxcc;
		req.qsoNotBefore = wiz.qsonotbefore;
		req.qsoNotAfter = wiz.qsonotafter;
		req.signer = wiz.cert;
		if (req.signer) {
			char buf[40];
			void *call = 0;
			if (!tqsl_getCertificateCallSign(req.signer, buf, sizeof(buf)))
				call = &buf;
			while (tqsl_beginSigning(req.signer, 0, getPassword, call)) {
				if (tQSL_Error != TQSL_PASSWORD_ERROR) {
					wxLogError(wxT("%hs"), tqsl_getErrorString());
					return;
				}
				if (tqsl_beginSigning(req.signer, unipwd, NULL, call)) {
					break;
				}
				if (tQSL_Error != TQSL_PASSWORD_ERROR) {
					wxLogError(wxT("%hs"), tqsl_getErrorString());
					return;
				}
			}
		}
		req.renew = renew ? 1 : 0;
		if (tqsl_createCertRequest(tqslName(file), &req, 0, 0)) {
			if (req.signer)
				tqsl_endSigning(req.signer);
			const char *msg = tqsl_getErrorString();
			wxLogError(wxT("%hs"), msg);
			wxMessageBox(wxString::Format(wxT("Error creating callsign certificate request: %hs"), msg), wxT("Error creating Callsign Certificate Request"), wxOK|wxICON_EXCLAMATION);
			return;
		}
		if (upload) {
			ifstream in(tqslName(file), ios::in | ios::binary);
			if (!in) {
				wxLogError(wxT("Error opening certificate request file %s: %hs"), file.c_str(), strerror(errno));
			} else {
				string contents;
				in.seekg(0, ios::end);
				contents.resize(in.tellg());
				in.seekg(0, ios::beg);
				in.read(&contents[0], contents.size());
				in.close();

				wxString fileType(wxT("Certificate Request"));
				retval = UploadFile(file, tqslName(file), 0, reinterpret_cast<void *>(const_cast<char *>(contents.c_str())),
							contents.size(), fileType);
				if (retval != 0)
					wxLogError(wxT("Your certificate request did not upload properly\nPlease try again."));
			}
		} else {
			wxString msg = wxT("You may now send your new certificate request (");
			msg += file;
			msg += wxT(")");
			if (wiz.provider.emailAddress[0] != 0)
				msg += wxString(wxT("\nto:\n   ")) + wxString::FromUTF8(wiz.provider.emailAddress);
			if (wiz.provider.url[0] != 0) {
				msg += wxT("\n");
				if (wiz.provider.emailAddress[0] != 0)
					msg += wxT("or ");
				msg += wxString(wxT("see:\n   ")) + wxString::FromUTF8(wiz.provider.url);
			}
			wxMessageBox(msg, wxT("TQSL"));
		}
		if (retval == 0) {
			wxString pending = wxConfig::Get()->Read(wxT("RequestPending"));
			if (pending.IsEmpty())
				pending = wiz.callsign;
			else
				pending += wxT(",") + wiz.callsign;
			wxConfig::Get()->Write(wxT("RequestPending"), pending);
		}
		if (req.signer)
			tqsl_endSigning(req.signer);
		cert_tree->Build(CERTLIST_FLAGS);
		CertTreeReset();
	}
}

void
MyFrame::CertTreeReset() {
	if (!cert_save_label) return;
	cert_save_label->SetLabel(wxT("\nSave a Callsign Certificate"));
	cert_renew_label->SetLabel(wxT("\nRenew a Callsign Certificate"));
	cert_prop_label->SetLabel(wxT("\nDisplay a Callsign Certificate"));
	cert_menu->Enable(tc_c_Renew, false);
	cert_renew_button->Enable(false);
	cert_select_label->SetLabel(wxT("\nSelect a Callsign Certificate to process"));
	cert_save_button->Enable(false);
	cert_prop_button->Enable(false);
}

void MyFrame::OnCertTreeSel(wxTreeEvent& event) {
	tqslTrace("MyFrame::OnCertTreeSel");
	wxTreeItemId id = event.GetItem();
	CertTreeItemData *data = reinterpret_cast<CertTreeItemData *>(cert_tree->GetItemData(id));
	if (data) {
		int keyonly = 0;
		int expired = 0;
		int superseded = 0;
		char call[40];
		tqsl_getCertificateCallSign(data->getCert(), call, sizeof call);
		wxString callSign = wxString::FromUTF8(call);
		tqsl_getCertificateKeyOnly(data->getCert(), &keyonly);
		tqsl_isCertificateExpired(data->getCert(), &expired);
		tqsl_isCertificateSuperceded(data->getCert(), &superseded);
		tqslTrace("MyFrame::OnCertTreeSel", "call=%s", call);

		cert_select_label->SetLabel(wxT(""));
		cert_menu->Enable(tc_c_Properties, true);
		cert_menu->Enable(tc_c_Export, true);
		cert_menu->Enable(tc_c_Delete, true);
		cert_menu->Enable(tc_c_Renew, true);
		cert_save_button->Enable(true);
		cert_load_button->Enable(true);
		cert_prop_button->Enable(true);

		int w, h;
		loc_add_label->GetSize(&w, &h);
		cert_save_label->SetLabel(wxT("\nSave the callsign certificate for ") + callSign);
		cert_save_label->Wrap(w - 10);
		cert_prop_label->SetLabel(wxT("\nDisplay the callsign certificate properties for ") + callSign);
		cert_prop_label->Wrap(w - 10);
		if (!(keyonly || expired || superseded)) {
			cert_renew_label->SetLabel(wxT("\nRenew the callsign certificate for ") + callSign);
			cert_renew_label->Wrap(w - 10);
		} else {
			cert_renew_label->SetLabel(wxT("\nRenew a Callsign Certificate"));
		}
		cert_menu->Enable(tc_c_Renew, !(keyonly || expired || superseded));
		cert_renew_button->Enable(!(keyonly || expired || superseded));
	} else {
		CertTreeReset();
	}
}

void MyFrame::OnCertProperties(wxCommandEvent& WXUNUSED(event)) {
	tqslTrace("MyFrame::OnCertProperties");
	CertTreeItemData *data = reinterpret_cast<CertTreeItemData *>(cert_tree->GetItemData(cert_tree->GetSelection()));
	if (data != NULL)
		displayCertProperties(data, this);
}

void MyFrame::OnCertExport(wxCommandEvent& WXUNUSED(event)) {
	tqslTrace("MyFrame::OnCertExport");
	CertTreeItemData *data = reinterpret_cast<CertTreeItemData *>(cert_tree->GetItemData(cert_tree->GetSelection()));
	if (data == NULL)	// "Never happens"
		return;

	char call[40];
	if (tqsl_getCertificateCallSign(data->getCert(), call, sizeof call)) {
		wxLogError(wxT("%hs"), tqsl_getErrorString());
		return;
	}
	tqslTrace("MyFrame::OnCertExport", "call=%s", call);
	wxString file_default = flattenCallSign(wxString::FromUTF8(call));
	int ko = 0;
	tqsl_getCertificateKeyOnly(data->getCert(), &ko);
	if (ko)
		file_default += wxT("-key-only");
	file_default += wxT(".p12");
	wxString path = wxConfig::Get()->Read(wxT("CertFilePath"), wxT(""));
	wxString filename = wxFileSelector(wxT("Enter the name for the new Certificate Container file"), path,
		file_default, wxT(".p12"), wxT("Certificate Container files (*.p12)|*.p12|All files (*.*)|*.*"),
		wxFD_SAVE|wxFD_OVERWRITE_PROMPT, this);
	if (filename == wxT(""))
		return;
	wxConfig::Get()->Write(wxT("CertFilePath"), wxPathOnly(filename));
	GetNewPasswordDialog dial(this, wxT("Certificate Container Password"),
wxT("Enter the password for the certificate container file.\n\n")
wxT("If you are using a computer system that is shared\n")
wxT("with others, you should specify a password to\n")
wxT("protect this certificate. However, if you are using\n")
wxT("a computer in a private residence, no password need be specified.\n\n")
wxT("You will have to enter the password any time you\n")
wxT("load the file into TrustedQSL\n\n")
wxT("Leave the password blank and click 'OK' unless you want to\n")
wxT("use a password.\n\n"), true, help, wxT("save.htm"));
	if (dial.ShowModal() != wxID_OK)
		return;	// Cancelled
	int terr;
	do {
		terr = tqsl_beginSigning(data->getCert(), 0, getPassword, reinterpret_cast<void *>(&call));
		if (terr) {
			if (tQSL_Error == TQSL_PASSWORD_ERROR) {
				terr = tqsl_beginSigning(data->getCert(), unipwd, NULL, reinterpret_cast<void *>(&call));
				if (terr) {
					if (tQSL_Error == TQSL_PASSWORD_ERROR)
						continue;
					wxLogError(wxT("%hs"), tqsl_getErrorString());
				}
				continue;
			}
			if (tQSL_Error == TQSL_OPERATOR_ABORT)
				return;
			wxLogError(wxT("%hs"), tqsl_getErrorString());
		}
	} while (terr);
	// When setting the password, always use UTF8.
	if (tqsl_exportPKCS12File(data->getCert(), tqslName(filename), dial.Password().ToUTF8()))
		wxLogError(wxT("Export to %s failed: %hs"), filename.c_str(), tqsl_getErrorString());
	else
		wxLogMessage(wxT("Certificate saved in file %s"), filename.c_str());
	tqsl_endSigning(data->getCert());
}

void MyFrame::OnCertDelete(wxCommandEvent& WXUNUSED(event)) {
	tqslTrace("MyFrame::OnCertDelete");
	CertTreeItemData *data = reinterpret_cast<CertTreeItemData *>(cert_tree->GetItemData(cert_tree->GetSelection()));
	if (data == NULL)	// "Never happens"
		return;

	if (wxMessageBox(
wxT("WARNING! BE SURE YOU REALLY WANT TO DO THIS!\n\n")
wxT("This will permanently remove the certificate from your system.\n")
wxT("You will NOT be able to recover it by loading a .TQ6 file.\n")
wxT("You WILL be able to recover it from a container (.p12) file only if you have\n")
wxT("created one via the Callsign Certificate menu's 'Save Callsign Certificate' command.\n\n")
wxT("ARE YOU SURE YOU WANT TO DELETE THE CERTIFICATE?"), wxT("Warning"), wxYES_NO|wxICON_QUESTION, this) == wxYES) {
		char buf[128];
		if (!tqsl_getCertificateCallSign(data->getCert(), buf, sizeof buf)) {
			wxString call = wxString::FromUTF8(buf);
			wxString pending = wxConfig::Get()->Read(wxT("RequestPending"));
			pending.Replace(call, wxT(""), true);
			wxString rest;
			while (pending.StartsWith(wxT(","), &rest))
				pending = rest;
			while (pending.EndsWith(wxT(","), &rest))
				pending = rest;
			wxConfig::Get()->Write(wxT("RequestPending"), pending);
		}
		if (tqsl_deleteCertificate(data->getCert()))
			wxLogError(wxT("%hs"), tqsl_getErrorString());
		cert_tree->Build(CERTLIST_FLAGS);
		CertTreeReset();
	}
}

void
MyFrame::LocTreeReset() {
	if (!loc_edit_button) return;
	loc_edit_button->Disable();
	loc_delete_button->Disable();
	loc_prop_button->Disable();
	stn_menu->Enable(tm_s_Properties, false);
	loc_edit_label->SetLabel(wxT("\nEdit a Station Location"));
	loc_delete_label->SetLabel(wxT("\nDelete a Station Location"));
	loc_prop_label->SetLabel(wxT("\nDisplay Station Location Properties"));
	loc_select_label->SetLabel(wxT("\nSelect a Station Location to process"));
}

void MyFrame::OnLocTreeSel(wxTreeEvent& event) {
	tqslTrace("MyFrame::OnLocTreeSel");
	wxTreeItemId id = event.GetItem();
	LocTreeItemData *data = reinterpret_cast<LocTreeItemData *>(loc_tree->GetItemData(id));
	if (data) {
		int w, h;
		wxString lname = data->getLocname();
		wxString call = data->getCallSign();
		tqslTrace("MyFrame::OnLocTreeSel", "lname=%s, call=%s", S(lname), S(call));

		loc_add_label->GetSize(&w, &h);

		loc_edit_button->Enable();
		loc_delete_button->Enable();
		loc_prop_button->Enable();
		stn_menu->Enable(tm_s_Properties, true);
		loc_edit_label->SetLabel(wxT("Edit Station Location ") + call + wxT(": ") + lname);
		loc_edit_label->Wrap(w - 10);
		loc_delete_label->SetLabel(wxT("Delete Station Location ") + call + wxT(": ") + lname);
		loc_delete_label->Wrap(w - 10);
		loc_prop_label->SetLabel(wxT("Display Station Location Properties for ") + call + wxT(": ") + lname);
		loc_prop_label->Wrap(w - 10);
		loc_select_label->SetLabel(wxT(""));
	} else {
		LocTreeReset();
	}
}

void MyFrame::OnLocProperties(wxCommandEvent& WXUNUSED(event)) {
	tqslTrace("MyFrame::OnLocProperties");
	LocTreeItemData *data = reinterpret_cast<LocTreeItemData *>(loc_tree->GetItemData(loc_tree->GetSelection()));
	if (data != NULL)
		displayLocProperties(data, this);
}

void MyFrame::OnLocDelete(wxCommandEvent& WXUNUSED(event)) {
	tqslTrace("MyFrame::OnLocDelete");
	LocTreeItemData *data = reinterpret_cast<LocTreeItemData *>(loc_tree->GetItemData(loc_tree->GetSelection()));
	if (data == NULL)	// "Never happens"
		return;

	if (wxMessageBox(
wxT("This will permanently remove this station location from your system.\n")
wxT("ARE YOU SURE YOU WANT TO DELETE THIS LOCATION?"), wxT("Warning"), wxYES_NO|wxICON_QUESTION, this) == wxYES) {
		if (tqsl_deleteStationLocation(data->getLocname().ToUTF8()))
			wxLogError(wxT("%hs"), tqsl_getErrorString());
		loc_tree->Build();
		LocTreeReset();
	}
}

void MyFrame::OnLocEdit(wxCommandEvent& WXUNUSED(event)) {
	tqslTrace("MyFrame::OnLocEdit");
	LocTreeItemData *data = reinterpret_cast<LocTreeItemData *>(loc_tree->GetItemData(loc_tree->GetSelection()));
	if (data == NULL)	// "Never happens"
		return;

	tQSL_Location loc;
	wxString selname;
	char errbuf[512];

	check_tqsl_error(tqsl_getStationLocation(&loc, data->getLocname().ToUTF8()));
	if (verify_cert(loc, true)) {	// Check if there is a certificate before editing
		check_tqsl_error(tqsl_getStationLocationErrors(loc, errbuf, sizeof(errbuf)));
		if (strlen(errbuf) > 0) {
			wxMessageBox(wxString::Format(wxT("%hs\nThe invalid data was ignored."), errbuf), wxT("Station Location data error"), wxOK|wxICON_EXCLAMATION, this);
		}
		char loccall[512];
		check_tqsl_error(tqsl_getLocationCallSign(loc, loccall, sizeof loccall));
		selname = run_station_wizard(this, loc, help, true, wxString::Format(wxT("Edit Station Location : %hs - %s"), loccall, data->getLocname().c_str()));
		check_tqsl_error(tqsl_endStationLocationCapture(&loc));
	}
	loc_tree->Build();
	LocTreeReset();
}

void MyFrame::OnLoginToLogbook(wxCommandEvent& WXUNUSED(event)) {
	tqslTrace("MyFrame::OnLoginToLogbook");
	wxString url = wxConfig::Get()->Read(wxT("LogbookURL"), DEFAULT_LOTW_LOGIN_URL);
	if (!url.IsEmpty())
		wxLaunchDefaultBrowser(url);
	return;
}

class CertPropDial : public wxDialog {
 public:
	CertPropDial(tQSL_Cert cert, wxWindow *parent = 0);
	void closeMe(wxCommandEvent&) { wxWindow::Close(TRUE); }
	DECLARE_EVENT_TABLE()
};

BEGIN_EVENT_TABLE(CertPropDial, wxDialog)
	EVT_BUTTON(tc_CertPropDialButton, CertPropDial::closeMe)
END_EVENT_TABLE()

CertPropDial::CertPropDial(tQSL_Cert cert, wxWindow *parent)
		: wxDialog(parent, -1, wxT("Certificate Properties"), wxDefaultPosition, wxSize(400, 15 * LABEL_HEIGHT)) {
	tqslTrace("CertPropDial::CertPropDial", "cert=%lx", static_cast<void *>(cert));
	const char *labels[] = {
		"Begins: ", "Expires: ", "Organization: ", "", "Serial: ", "Operator: ",
		"Call sign: ", "DXCC Entity: ", "QSO Start Date: ", "QSO End Date: ", "Key: "
	};

	wxBoxSizer *topsizer = new wxBoxSizer(wxVERTICAL);
	wxBoxSizer *prop_sizer = new wxBoxSizer(wxVERTICAL);

	int y = 10;
	for (int i = 0; i < static_cast<int>(sizeof labels / sizeof labels[0]); i++) {
		wxBoxSizer *line_sizer = new wxBoxSizer(wxHORIZONTAL);
		wxStaticText *st = new wxStaticText(this, -1, wxString::FromUTF8(labels[i]),
			wxDefaultPosition, wxSize(LABEL_WIDTH, LABEL_HEIGHT), wxALIGN_RIGHT);
		line_sizer->Add(st);
		char buf[128] = "";
		tQSL_Date date;
		int dxcc, keyonly;
		DXCC DXCC;
		long serial;
		switch (i) {
                        case 0:
				tqsl_getCertificateKeyOnly(cert, &keyonly);
				if (keyonly)
					strncpy(buf, "N/A", sizeof buf);
				else if (!tqsl_getCertificateNotBeforeDate(cert, &date))
					tqsl_convertDateToText(&date, buf, sizeof buf);
				break;
                        case 1:
				tqsl_getCertificateKeyOnly(cert, &keyonly);
				if (keyonly)
					strncpy(buf, "N/A", sizeof buf);
				else if (!tqsl_getCertificateNotAfterDate(cert, &date))
					tqsl_convertDateToText(&date, buf, sizeof buf);
				break;
                        case 2:
				tqsl_getCertificateIssuerOrganization(cert, buf, sizeof buf);
				break;
                        case 3:
				tqsl_getCertificateIssuerOrganizationalUnit(cert, buf, sizeof buf);
				break;
                        case 4:
				tqsl_getCertificateKeyOnly(cert, &keyonly);
				if (keyonly) {
					strncpy(buf, "N/A", sizeof buf);
				} else {
					tqsl_getCertificateSerial(cert, &serial);
					snprintf(buf, sizeof buf, "%ld", serial);
				}
				break;
                        case 5:
				tqsl_getCertificateKeyOnly(cert, &keyonly);
				if (keyonly)
					strncpy(buf, "N/A", sizeof buf);
				else
					tqsl_getCertificateAROName(cert, buf, sizeof buf);
				break;
                        case 6:
				tqsl_getCertificateCallSign(cert, buf, sizeof buf);
				break;
                        case 7:
				tqsl_getCertificateDXCCEntity(cert, &dxcc);
				DXCC.getByEntity(dxcc);
				strncpy(buf, DXCC.name(), sizeof buf);
				break;
                        case 8:
				if (!tqsl_getCertificateQSONotBeforeDate(cert, &date))
					tqsl_convertDateToText(&date, buf, sizeof buf);
				break;
                        case 9:
				if (!tqsl_getCertificateQSONotAfterDate(cert, &date))
					tqsl_convertDateToText(&date, buf, sizeof buf);
				break;
                        case 10:
				switch (tqsl_getCertificatePrivateKeyType(cert)) {
                                        case TQSL_PK_TYPE_ERR:
						wxMessageBox(wxString::FromUTF8(tqsl_getErrorString()), wxT("Error"));
						strncpy(buf, "<ERROR>", sizeof buf);
						break;
                                        case TQSL_PK_TYPE_NONE:
						strncpy(buf, "None", sizeof buf);
						break;
                                        case TQSL_PK_TYPE_UNENC:
						strncpy(buf, "Unencrypted", sizeof buf);
						break;
                                        case TQSL_PK_TYPE_ENC:
						strncpy(buf, "Password protected", sizeof buf);
						break;
				}
				break;
		}
		line_sizer->Add(new wxStaticText(this, -1, wxString::FromUTF8(buf)));
		prop_sizer->Add(line_sizer);
		y += LABEL_HEIGHT;
	}
	topsizer->Add(prop_sizer, 0, wxALL, 10);
	topsizer->Add(
		new wxButton(this, tc_CertPropDialButton, wxT("Close")),
		0, wxALIGN_CENTER | wxALL, 10
	);
	SetAutoLayout(TRUE);
	SetSizer(topsizer);
	topsizer->Fit(this);
	topsizer->SetSizeHints(this);
	CenterOnParent();
}

void
displayCertProperties(CertTreeItemData *item, wxWindow *parent) {
	tqslTrace("displayCertProperties", "item=%lx", static_cast<void *>(item));
	if (item != NULL) {
		CertPropDial dial(item->getCert(), parent);
		dial.ShowModal();
	}
}


class LocPropDial : public wxDialog {
 public:
	LocPropDial(wxString locname, wxWindow *parent = 0);
	void closeMe(wxCommandEvent&) { wxWindow::Close(TRUE); }
	DECLARE_EVENT_TABLE()
};

BEGIN_EVENT_TABLE(LocPropDial, wxDialog)
	EVT_BUTTON(tl_LocPropDialButton, LocPropDial::closeMe)
END_EVENT_TABLE()

LocPropDial::LocPropDial(wxString locname, wxWindow *parent)
		: wxDialog(parent, -1, wxT("Station Location Properties"), wxDefaultPosition, wxSize(1000, 15 * LABEL_HEIGHT)) {
	tqslTrace("LocPropDial", "locname=%s", S(locname));

	const char *fields[] = { "CALL", "Call sign: ",
				 "DXCC", "DXCC Entity: ",
				 "GRIDSQUARE", "Grid Square: ",
				 "ITUZ", "ITU Zone: ",
				 "CQZ", "CQ Zone: ",
				 "IOTA", "IOTA Locator: ",
				 "US_STATE", "State: ",
				 "US_COUNTY", "County: ",
				 "CA_PROVINCE", "Province: ",
				 "RU_OBLAST", "Oblast: ",
				 "CN_PROVINCE", "Province: ",
				 "AU_STATE", "State: " };

	tQSL_Location loc;
	check_tqsl_error(tqsl_getStationLocation(&loc, locname.ToUTF8()));

	wxBoxSizer *topsizer = new wxBoxSizer(wxVERTICAL);
	wxBoxSizer *prop_sizer = new wxBoxSizer(wxVERTICAL);

	int y = 10;
	char fieldbuf[512];
	for (int i = 0; i < static_cast<int>(sizeof fields / sizeof fields[0]); i+=2) {
		if (tqsl_getStationLocationField(loc, fields[i], fieldbuf, sizeof fieldbuf) == 0) {
			if (strlen(fieldbuf) > 0) {
				wxBoxSizer *line_sizer = new wxBoxSizer(wxHORIZONTAL);
				wxStaticText *st = new wxStaticText(this, -1, wxString::FromUTF8(fields[i+1]),
					wxDefaultPosition, wxSize(LABEL_WIDTH, LABEL_HEIGHT), wxALIGN_RIGHT);
				line_sizer->Add(st, 30);
				if (!strcmp(fields[i], "DXCC")) {
					int dxcc = strtol(fieldbuf, NULL, 10);
					const char *dxccname = NULL;
					tqsl_getDXCCEntityName(dxcc, &dxccname);
					strncpy(fieldbuf, dxccname, sizeof fieldbuf);
				}
				line_sizer->Add(
					new wxStaticText(this, -1, wxString::FromUTF8(fieldbuf),
					wxDefaultPosition, wxSize(LABEL_WIDTH, LABEL_HEIGHT)), 70);
				prop_sizer->Add(line_sizer);
				y += LABEL_HEIGHT;
			}
		}
	}
	topsizer->Add(prop_sizer, 0, wxALL, 10);
	topsizer->Add(
		new wxButton(this, tl_LocPropDialButton, wxT("Close")),
				0, wxALIGN_CENTER | wxALL, 10
	);
	SetAutoLayout(TRUE);
	SetSizer(topsizer);
	topsizer->Fit(this);
	topsizer->SetSizeHints(this);
	CenterOnParent();
}

void
displayLocProperties(LocTreeItemData *item, wxWindow *parent) {
	tqslTrace("displayLocProperties", "item=%lx", item);
	if (item != NULL) {
		LocPropDial dial(item->getLocname(), parent);
		dial.ShowModal();
	}
}

int
getPassword(char *buf, int bufsiz, void *callsign) {
	tqslTrace("getPassword", "buf=%lx, bufsiz=%d, callsign=%s", buf, bufsiz, callsign ? callsign : "NULL");
	wxString prompt(wxT("Enter the password to unlock the callsign certificate"));

	if (callsign)
	    prompt = prompt + wxT(" for ") + wxString::FromUTF8((const char *)callsign);

	tqslTrace("getPassword", "Probing for top window");
	wxWindow* top = wxGetApp().GetTopWindow();
	tqslTrace("getPassword", "Top window = 0x%lx", reinterpret_cast<void *>(top));
	top->SetFocus();
	tqslTrace("getPassword", "Focus grabbed. About to pop up password dialog");
	GetPasswordDialog dial(top, wxT("Enter password"), prompt);
	if (dial.ShowModal() != wxID_OK) {
		tqslTrace("getPassword", "Password entry cancelled");
		return 1;
	}
	tqslTrace("getPassword", "Password entered OK");
	strncpy(buf, dial.Password().ToUTF8(), bufsiz);
	utf8_to_ucs2(buf, unipwd, sizeof unipwd);
	buf[bufsiz-1] = 0;
	return 0;
}

void
displayTQSLError(const char *pre) {
	tqslTrace("displayTQSLError", "pre=%s", pre);
	wxString s = wxString::FromUTF8(pre);
	s += wxT(":\n");
	s += wxString::FromUTF8(tqsl_getErrorString());
	wxMessageBox(s, wxT("Error"));
}


static wxString
flattenCallSign(const wxString& call) {
	tqslTrace("flattenCallSign", "call=%s", S(call));
	wxString flat = call;
	size_t idx;
	while ((idx = flat.find_first_not_of(wxT("ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890_"))) != wxString::npos)
		flat[idx] = '_';
	return flat;
}

void tqslTrace(const char *name, const char *format, ...) {
	va_list ap;
	if (!diagFile) return;

	time_t t = time(0);
	char timebuf[50];
	strncpy(timebuf, ctime(&t), sizeof timebuf);
	timebuf[strlen(timebuf) - 1] = '\0';		// Strip the newline
	fprintf(diagFile, "%s %s: ", timebuf, name);
	if (!format) {
		fprintf(diagFile, "\r\n");
		fflush(diagFile);
		return;
	}
	va_start(ap, format);
	vfprintf(diagFile, format, ap);
	va_end(ap);
	fprintf(diagFile, "\r\n");
	fflush(diagFile);
}

static int lockfileFD = -1;

#ifndef _WIN32
static int
lock_db(bool wait) {
	struct flock fl;
	fl.l_type = F_WRLCK;
	fl.l_whence = SEEK_SET;
	fl.l_start = 0;
	fl.l_len = 1;

	wxString lfname = wxString::FromUTF8(tQSL_BaseDir) + wxT("/dblock");

	if (lockfileFD < 0) {
		lockfileFD = open(tqslName(lfname), O_RDWR| O_CREAT, 0644);
		if (lockfileFD < 0)
			return 1;
	}
	if (wait) {
		fcntl(lockfileFD, F_SETLKW, &fl);
		return 0;
	}
	int ret = fcntl(lockfileFD, F_SETLK, &fl);
	if (ret < 0 && (errno == EACCES || errno == EAGAIN)) {
		return -1;
	}
	return 0;
}

static void
unlock_db(void) {
	if (lockfileFD < 0) return;
	close(lockfileFD);
	lockfileFD = -1;
	return;
}
#else /* _WIN32 */

static OVERLAPPED ov;
static HANDLE hFile;

static int
lock_db(bool wait) {
	BOOL ret = FALSE;
	DWORD locktype = LOCKFILE_EXCLUSIVE_LOCK;

	wxString lfname = wxString::FromUTF8(tQSL_BaseDir) + wxT("\\dblock");

	if (lockfileFD < 0) {
		lockfileFD = _open(tqslName(lfname), O_RDWR| O_CREAT, 0644);
		if (lockfileFD < 0)
			return 1;
		ZeroMemory(&ov, sizeof(ov));
		ov.hEvent = NULL;
		ov.Offset = 0;
		ov.OffsetHigh = 0x80000000;
	}

	hFile = (HANDLE) _get_osfhandle(lockfileFD);

	if (!wait) {
		locktype |= LOCKFILE_FAIL_IMMEDIATELY;
	}
	ret = LockFileEx(hFile, locktype, 0, 0, 0x80000000, &ov);
	if (!ret) {
		switch (GetLastError()) {
			case ERROR_SHARING_VIOLATION:
			case ERROR_LOCK_VIOLATION:
			case ERROR_IO_PENDING:
				return -1;
			default:
				return 0;
		}
	}
	return 0;
}

static void
unlock_db(void) {
	UnlockFileEx(hFile, 0, 0, 0x80000000, &ov);
	_close(lockfileFD);
	lockfileFD = -1;
}
#endif /* _WIN32 */