summaryrefslogtreecommitdiff
path: root/mbgctrl/mbgctrl.c
blob: e98ca6be356766e9b78b679655541c24143aad52 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502

/**************************************************************************
 *
 *  $Id: mbgctrl.c 1.33 2021/11/15 17:08:54Z martin.burnicki REL_M $
 *
 *  Description:
 *    Main file for mbgctrl program which sends commands and
 *    configuration parameters to a Meinberg device via IOCTL calls.
 *
 * -----------------------------------------------------------------------
 *  $Log: mbgctrl.c $
 *  Revision 1.33  2021/11/15 17:08:54Z  martin.burnicki
 *  Improved printing of usage information.
 *  Revision 1.32  2021/11/08 18:01:31  martin.burnicki
 *  Account for modified MBG_DEV_FN type.
 *  Revision 1.31  2021/04/12 21:57:56  martin
 *  Updated printing of usage information.
 *  Revision 1.30  2021/03/22 17:56:13  martin
 *  Updated a bunch of comments, and a few output messages.
 *  Revision 1.29  2021/03/12 11:49:28  martin
 *  Corrected the wording of some comments.
 *  Revision 1.28  2020/02/24 11:17:46  martin
 *  Removed inclusion of obsolete header pcpsutil.h.
 *  Revision 1.27  2018/12/14 12:49:49  martin
 *  Introduced new command COLDBOOT.
 *  Use new function mbg_open_device_by_param_chk().
 *  Fixed compiler warnings and doxygen comment.
 *  Revision 1.26  2018/12/11 12:07:50  martin
 *  Fixed compiler warnings on Windows.
 *  Revision 1.25  2018/11/15 12:12:37Z  martin
 *  Individual MBG_MICRO_VERSION codes are now obsolete.
 *  Revision 1.24  2018/09/21 16:12:23  martin
 *  Account for renamed library symbols.
 *  Revision 1.23  2017/07/05 19:10:07  martin
 *  New way to maintain version information.
 *  Support build on Windows.
 *  Bugfix: accept parameter keyword only when substring is found at the
 *  start of the parameter string.
 *  Support configuring PTP parameters incl. unicast
 *  Warn if trying to handle serial port cfg but no serial port is supported.
 *  Basic support for programmable pulse outputs, including pulse shift feature.
 *  Yet incomplete support for synthesizer output.
 *  Use more functions from common library modules.
 *  Use codes and inline functions from mbgerror.h.
 *  Proper return codes and exit codes.
 *  Revision 1.22  2009/09/29 14:58:18  martin
 *  Unified and simplified parameter evaluation.
 *  Updated version number to 3.4.0.
 *  Revision 1.21  2009/09/28 09:36:43  martin
 *  Support configuration of antenna cable length.
 *  Removed duplicate usage message for event time.
 *  Revision 1.20  2009/09/28 07:19:03  martin
 *  Made parameter syntax for enable_flags and LAN configuration more flexible.
 *  Revision 1.19  2009/08/20 14:19:29  martin
 *  Updated version number to 3.3.1.
 *  Support configuration of board's LAN interface.
 *  Revision 1.18  2009/07/24 09:50:08  martin
 *  Updated version number to 3.3.0.
 *  Revision 1.17  2009/06/19 12:38:51  martin
 *  Updated version number to 3.2.0.
 *  Revision 1.16  2009/06/18 15:14:53  martin
 *  Added command TZOFFS which can be used to set TZDL to UTC, and then
 *  configure the standard TZDL offset to a dedicated number of seconds, to the
 *  output time has a configurable UTC offset against the time derived from the
 *  input signal.
 *  Revision 1.15  2009/03/20 11:53:19  martin
 *  Updated version number to 3.1.0.
 *  Updated copyright year to include 2009.
 *  Support programmable time scales.
 *  Revision 1.14  2008/12/22 12:39:00  martin
 *  Updated description, copyright, revision number and string.
 *  Use unified functions from toolutil module.
 *  Accept device name(s) on the command line.
 *  Don't use printf() without format, which migth produce warnings
 *  with newer gcc versions.
 *  Revision 1.13  2008/11/07 10:25:49  martin
 *  Support modification of the ENABLE_FLAGS of a device.
 *  Changes due to renamed library function.
 *  Changes due to renamed library function.
 *  Revision 1.12  2008/09/15 14:20:21  martin
 *  Support generic serial settings including string type and mode.
 *  Reworked evaluation of command line parameters.
 *  New parameter COM0= to configure an individual port.
 *  Account for renamed library symbols.
 *  Revision 1.11  2007/07/24 09:31:39  martin
 *  Changes due to renamed library symbols.
 *  Revision 1.10  2007/03/01 16:09:16  martin
 *  Be able to set the board date and/or time.
 *  Revision 1.9  2007/02/22 16:38:50  martin
 *  Added function to set on-board date.
 *  Revision 1.8  2006/08/28 10:45:50  martin
 *  Picked up Heiko's patch to set the GPS receiver position.
 *  Revision 1.7  2004/11/08 15:47:40  martin
 *  Using type cast to avoid compiler warning.
 *  Revision 1.6  2003/08/26 14:37:35  martin
 *  Support configuration of some standard time zones,
 *  also for GPS devices.
 *  Revision 1.5  2003/07/31 13:48:54  martin
 *  Added function to set COM port parms for GPS devices.
 *  Usage shows which parameters are supported by a device.
 *  Revision 1.4  2003/04/25 10:27:58  martin
 *  Use new functions from mbgdevio library.
 *  New program version v2.1.
 *  Revision 1.3  2002/08/22 14:52:49  martin
 *  Added function to set COM port parameters of a device.
 *  Revision 1.2  2001/12/03 16:04:46  martin
 *  New program version 1.2.
 *  Added new function set_event_time().
 *  Fixed a bug in eval of cmd line parameters.
 *  Revision 1.1  2001/09/17 15:07:56  martin
 *
 **************************************************************************/

// Include Meinberg headers.
#include <mbgdevio.h>
#include <deviohlp.h>
#include <pcpsmktm.h>
#include <cfg_hlp.h>
#include <myutil.h>
#include <gpsutils.h>
#include <cnv_wday.h>
#include <toolutil.h>  // Common utility functions.
#include <ptp_util.h>
#include <lan_util.h>
#include <str_util.h>

// Include system headers.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <ctype.h>


#define MBG_FIRST_COPYRIGHT_YEAR   2001
#define MBG_LAST_COPYRIGHT_YEAR    0     // Use default.

#define RC_USAGE 1

static const char *pname = "mbgctrl";

static char *dev_name;

static int err_unicast_nsupp;

static const char str_spc_not[] = " not";
static const char str_spc_not_supp[] = " (not supported)";
static const char str_spc_wildcard[] = " (wildcard)";

static TZDL tzdl_utc = DEFAULT_TZDL_UTC;
static TZDL tzdl_cet_cest = DEFAULT_TZDL_CET_CEST_EN;
static TZDL tzdl_eet_eest = DEFAULT_TZDL_EET_EEST_EN;
static long max_tzdl_offs = 0x7FFFFFFFL;   // Max. val for int32_t.

static const char tz_info_utc[] = TZ_INFO_UTC;
static const char tz_info_cet_cest[] = TZ_INFO_CET_CEST_EN;
static const char tz_info_eet_eest[] = TZ_INFO_EET_EEST_EN;

static const char *mode_names[N_STR_MODE] = DEFAULT_ENG_MODE_NAMES;

static const char *time_scale_names[N_MBG_TIME_SCALE] = MBG_TIME_SCALE_STRS;

#define _get_time_scale_name( _i ) \
  ( ( (_i) < N_MBG_TIME_SCALE ) ? time_scale_names[_i] : str_unknown )

static const char * const pout_mode_names_eng[N_POUT_MODES] = DEFAULT_ENG_POUT_NAMES;

#define _get_pout_mode_name( _i ) \
  ( ( (_i) < N_POUT_MODES ) ? pout_mode_names_eng[_i] : str_unknown )


static const char no_gps_cmd[] = "does not support GPS commands";
static const char no_tzdl[] = "does not support configurable time zone";
static const char no_tz[] = "does not support time zones";
static const char no_synth[] = "has no synthesizer output";
static const char no_event_time[] = "does not support event times";
static const char no_enable_flags[] = "does not support enable flags";
static const char no_time_scale[] = "does not support a configurable time scale";
static const char no_lan_intf[] = "has no LAN interface";
static const char no_ptp[] = "does not provide PTP";
static const char no_cab_len[] = "does not support antenna signal delay compensation";



/**
 * @brief A type used to pass print control flags to functions.
 *
 * @see ::CTRL_FLAG_MASKS
 */
typedef int CTRL_FLAGS;


/**
 * @brief Flag masks used with ::CTRL_FLAGS.
 *
 * @see ::CTRL_FLAGS
 */
enum CTRL_FLAG_MASKS
{
  CTRL_PRINT_ALL = 0x01,
  CTRL_PRINT_NEWLINES = 0x02,
  CTRL_PRINT_IDX = 0x04,
  CTRL_PRINT_ERR = 0x08,
  CTRL_PRINT_PLUS = 0x10,
  CTRL_NOT_SUPP = 0x20
};


struct OPT_HANDLER_SPEC_S;

typedef int HELP_FNC( MBG_DEV_HANDLE, const PCPS_DEV *, const struct OPT_HANDLER_SPEC_S *, CTRL_FLAGS );
typedef int SET_FNC( MBG_DEV_HANDLE, const char *, int );
typedef int SHOW_FNC( MBG_DEV_HANDLE, const struct OPT_HANDLER_SPEC_S *, const PCPS_DEV *, const char * );

typedef struct OPT_HANDLER_SPEC_S
{
  const char *cmd_name;
  MBG_CHK_SUPP_FNC *chk_supp_fnc;
  HELP_FNC *help_fnc;
  SET_FNC *set_fnc;
  SHOW_FNC *show_fnc;
  const char *cmd_info;
  const char *not_supp_msg;
  uint32_t flags;  ///< See ::OPT_FLAG_MASKS.

} OPT_HANDLER_SPEC;


enum OPT_FLAG_BITS
{
  OPT_SUPP_CMD_IDX_BIT,  ///< E.g. COM0=, COM1=, etc. vs. TZ=.
  N_OPT_FLAG_BITS
};

enum OPT_FLAG_MASKS
{
  OPT_SUPP_CMD_IDX = ( 1UL << OPT_SUPP_CMD_IDX_BIT )  ///< See ::OPT_SUPP_CMD_IDX_BIT.
};

OPT_HANDLER_SPEC ohs_pout =
{
  "POUT",  // cmd_name
  NULL,    // chk_supp_fnc
  NULL,    // help_fnc
  NULL,    // set_fnc
  NULL,    // show_fnc
  NULL,    // cmd_info
  NULL,    // not_supp_msg
  OPT_SUPP_CMD_IDX  // flags
};



typedef struct
{
  int indent_1;
  int indent_2;
  int indent_3;
  int comm_col_x;
} INDENTS;

const INDENTS usage_indents = { 2, 4, 6, 30 };
const INDENTS usage_indents_detailed = { 4, 6, 8, 30 };
const INDENTS show_indents = { 2, 4, 0, 0 };


#define SHOW_INDENT_1   "  "
#define SHOW_INDENT_2   "    "



typedef struct
{
  const char *name;
  uint16_t *flags;
  uint16_t on_flags;
} EF_INFO;

#define N_EF_INFO  3

static const char ef_name_serial[] = "SERIAL";
static const char ef_name_pulses[] = "PULSES";
static const char ef_name_synth[] = "SYNTH";


typedef struct
{
  const char *name;
  IP4_ADDR *addr;
} IP4_INFO;

#define N_IP4_INFO 4

static const char ip4_name_ip[] = "IP";
static const char ip4_name_nm[] = "NM";
static const char ip4_name_ba[] = "BA";
static const char ip4_name_gw[] = "GW";

static const char ptp_name_net[] = "NP";
static const char ptp_name_del[] = "DM";
static const char ptp_name_dom[] = "DO";
static const char ptp_name_v1[] = "HW";

static const char ptp_name_role[] = "ROLE";

static const char ptp_name_gmip[] = "GMIP";
static const char ptp_name_gmid[] = "GMID";
static const char ptp_name_pid[] = "PID";
static const char ptp_name_smi[] = "SMI";
static const char ptp_name_ami[] = "AMI";
static const char ptp_name_dri[] = "DRI";
static const char ptp_name_dur[] = "DUR";

//##+++++
static const char *delay_mech[] = PTP_DELAY_MECH_NAMES;
static const char *nw_prot[] = PTP_NW_PROT_STRS;
static const char *nw_prot_short[] = PTP_NW_PROT_STRS_SHORT;

static const char *ptp_roles[] = PTP_ROLE_STRS;
static const char *ptp_roles_short[] = PTP_ROLE_STRS_SHORT;

static const PTP_CLOCK_ID clock_id_wildcard = PTP_CLOCK_ID_WILDCARD;

// If unicast is not supported for a PTP device, the device is definitely
// a multicast slave, in which case index 0 returns the correct role name.
#define _ptp_role_name( _i ) \
  ( ( (_i) < N_PTP_ROLES ) ? ptp_roles[_i] : str_unknown )

#define _ptp_role_name_short( _i ) \
  ( ( (_i) < N_PTP_ROLES ) ? ptp_roles_short[_i] : str_unknown )


static const char pout_name_mode[] = "MODE";
static const char pout_name_len[] = "LEN";
static const char pout_name_inv[] = "INV";
static const char pout_name_ois[] = "OIS";
static const char pout_name_shift[] = "SHIFT";



static /*HDR*/
__attribute__( ( format( printf, 4, 5 ) ) )
int usage_line( const INDENTS *p_ind, const OPT_HANDLER_SPEC *p_opt,
                const char *cmd_parm, const char *cmd_comment_fmt, ... )
{
  int n = 0;

  // Print left margin, if not 0.
  if ( p_ind->indent_1 )
    n += printf( "%*s", p_ind->indent_1, str_empty );

  // Print command name.
  if ( p_opt )
    n += printf( "%s", p_opt->cmd_name );

  // Print the command parameters, if specified.
  if ( cmd_parm )
  {
    if ( p_opt && ( p_opt->flags & OPT_SUPP_CMD_IDX ) )
      n+= printf( "%s", "<n>" );

    n += printf( "=%s", cmd_parm );
  }

  // Print command comment, which can be a format string
  // expecting additional parameters.
  if ( cmd_comment_fmt )
  {
    va_list arg_list;

    // Indent the comment string.
    if ( p_ind->indent_2 )
    {
      int w = p_ind->indent_2 - n;

      while ( w < 0 )
        w += 8;

      n += printf( "%*s", w, str_empty );
    }

    va_start( arg_list, cmd_comment_fmt );
    n += vprintf( cmd_comment_fmt, arg_list );
    va_end( arg_list );
  }

  n += printf( "\n" );

  return n;

}  // usage_line



static /*HDR*/
int print_indent( int i )
{
  int n = printf( "%*s", i, str_empty );

  return n;

}  // print_indent



static /*HDR*/
__attribute__( ( format( printf, 2, 3 ) ) )
int usage_note( int indent, const char *fmt, ... )
{
  // Print left margin, if not 0.
  int n = print_indent( indent );

  if ( fmt )
  {
    va_list arg_list;

    va_start( arg_list, fmt );
    n += vprintf( fmt, arg_list );
    n += printf( "\n" );
    va_end( arg_list );
  }

  return n;

}  // usage_note



typedef const char *(STR_FNC)( int idx );


static /*HDR*/
void print_bit_mask_list( const char *info_1, const char *info_2, uint32_t supp_mask,
                          int n_known, const char * const names[], STR_FNC *s_fnc,
                          int inst_idx, CTRL_FLAGS ctrl_flags, const INDENTS *p_ind )
{
  const char *str_s_fnc = s_fnc ? s_fnc( inst_idx ) : str_empty;

  print_indent( p_ind->indent_2 );

  if ( ctrl_flags & CTRL_PRINT_ALL )
  {
    supp_mask = ( 1UL << n_known ) - 1;

    if ( supp_mask )
      printf( "Known %s%s: ", info_1, str_s_fnc );
    else
      printf( "No %s%s known.", info_1, str_s_fnc );
  }
  else
  {
    if ( supp_mask )
    {
      printf( "%s", info_1 );

      if ( info_2 )
        printf( " %s", info_2 );

      #if defined( DEBUG )
        printf( " (%04lX)", (ulong) supp_mask );
      #endif

      printf( ":" );
    }
    else
    {
      printf( "No %s.", info_1 );

      if ( info_2 )
        printf( " %s", info_2 );

      printf( "." );
    }
  }


  if ( supp_mask )
  {
    int n_printed = 0;
    int i;
    const char *str_sep = ( ctrl_flags & CTRL_PRINT_PLUS ) ? "+" : ", ";

    for ( i = 0; i < n_known; i++ )
    {
      const char *cp;

      if ( ( supp_mask & ( 1UL << i ) ) == 0 )
        continue;

      if ( names )
        cp = names[i];
      else
        if ( s_fnc )
          cp = s_fnc( i );
        else
          cp = str_empty;

      if ( ctrl_flags & ( CTRL_PRINT_NEWLINES | CTRL_PRINT_IDX ) )
      {
        printf( "\n" );
        print_indent( p_ind->indent_3 );

        if ( ctrl_flags & CTRL_PRINT_IDX )
          printf( "%i: ", i );

        printf( "%s", cp );
      }
      else
        printf( "%s%s", n_printed ? str_sep : str_empty, cp );

      n_printed++;
    }
  }

  printf( "\n" );

}  // print_bit_mask_list



static /*HDR*/
void err_msg( const PCPS_DEV *p_dev, const char *msg )
{
  printf( "This device %s.\n", msg );

}  // err_msg



static /*HDR*/
int set_tz_code( MBG_DEV_HANDLE dh, PCPS_TZCODE tzcode, const char *info )
{
  int rc = mbg_set_tzcode( dh, &tzcode );

  if ( mbg_cond_err_msg( rc, "mbg_set_tzcode" ) )
    return rc;

  if ( info )
    printf( "The time zone configuration of the device has been set to %s.\n", info );

  return MBG_SUCCESS;

}  // set_tz_code



static /*HDR*/
int set_gps_tzdl( MBG_DEV_HANDLE dh, const TZDL *tzdl, const char *info )
{
  int rc = mbg_set_gps_tzdl( dh, tzdl );

  if ( mbg_cond_err_msg( rc, "set_gps_tzdl" ) )
    return rc;

  if ( info )
    printf( "The time zone configuration of the device has been set to %s.\n", info );

  return MBG_SUCCESS;

}  // set_gps_tzdl



static /*HDR*/
int set_timezone( MBG_DEV_HANDLE dh, const char *tz_name, const PCPS_DEV *p_dev )
{
  const char *tz_info = NULL;
  TZDL *tz_tzdl = NULL;
  PCPS_TZCODE tz_code = 0;
  int rc = MBG_SUCCESS;

  if ( strcmp( tz_name, "UTC" ) == 0 )
  {
    tz_info = tz_info_utc;
    tz_tzdl = &tzdl_utc;
    tz_code = PCPS_TZCODE_UTC;
  }
  else if ( strcmp( tz_name, "CET" ) == 0 )
  {
    tz_info = tz_info_cet_cest;
    tz_tzdl = &tzdl_cet_cest;
    tz_code = PCPS_TZCODE_MEZMESZ;
  }
  else if ( strcmp( tz_name, "EET" ) == 0 )
  {
    tz_info = tz_info_eet_eest;
    tz_tzdl = &tzdl_eet_eest;
    tz_code = PCPS_TZCODE_OEZ;
  }
  else
  {
    printf( "** Unknown timezone name %s\n", tz_name );
    rc = RC_USAGE;
  }

  if ( tz_info )
  {
    if ( _pcps_has_tzcode( p_dev ) )
      rc = set_tz_code( dh, tz_code, tz_info );
    else
      if ( _pcps_has_tzdl( p_dev ) )
        rc = set_gps_tzdl( dh, tz_tzdl, tz_info );
      else
        err_msg( p_dev, no_tz );
  }

  return rc;

}  // set_timezone



static /*HDR*/
int show_tzdl_offs( MBG_DEV_HANDLE dh, const char *info )
{
  TZDL tzdl;
  int rc = mbg_get_gps_tzdl( dh, &tzdl );

  if ( mbg_cond_err_msg( rc, "mbg_get_gps_tzdl" ) )
    return rc;

  printf( "%s timezone offset: UTC%+lis", info, (long) tzdl.offs );

  return MBG_SUCCESS;

}  // show_tzdl_offs



static /*HDR*/
int set_tzdl_offs( MBG_DEV_HANDLE dh, const char *s )
{
  TZDL tzdl = tzdl_utc;
  long tzdl_offs = atol( s );

  if ( labs( tzdl_offs ) > max_tzdl_offs )   // Max. val for int32_t.
  {
    fprintf( stderr, "** Time zone offset %li exceeds range (%li..%li)\n",
             tzdl_offs, -max_tzdl_offs, max_tzdl_offs );
    return MBG_ERR_CFG;
  }

  tzdl.offs = (int32_t) tzdl_offs;

  return set_gps_tzdl( dh, &tzdl, NULL );

}  // set_tzdl_offs



static /*HDR*/
int show_synth( MBG_DEV_HANDLE dh, const char *info )
{
  SYNTH synth;
  int rc = mbg_get_synth( dh, &synth );

  if ( mbg_cond_err_msg( rc, "mbg_get_synth" ) )
    return rc;

  printf( "%s synthesizer settings: freq %i.%iE%i Hz, phase %+i.%i deg", info,
          synth.freq / 10, synth.freq % 10, synth.range,
          synth.phase / 10, abs( synth.phase ) % 10 );

/*
  int16_t freq;    ///< four digits used; scale: 0.1 Hz; e.g. 1234 -> 123.4 Hz
  int16_t range;   ///< scale factor for freq; 0..::MAX_SYNTH_RANGE
  int16_t phase;   ///< -::MAX_SYNTH_PHASE..+::MAX_SYNTH_PHASE; >0 -> pulses later
*/
  return MBG_SUCCESS;

}  // show_synth



static /*HDR*/
int set_synth( MBG_DEV_HANDLE dh, const char *s )
{
  SYNTH synth = { 0 };
  char *cp;

  long freq = strtol( s, &cp, 10 ) * 10;

  if ( *cp == '.' )
  {
    long frac = strtol( ++cp, NULL, 10 );
    if ( frac < 0 || frac > 9 )
      goto fail;

    freq += frac;
  }

  synth.freq = (int16_t) freq;
  synth.range = 0;
  synth.phase = 0;

  return mbg_set_synth( dh, &synth );

fail:
  return MBG_ERR_INV_PARM;

}  // set_synth



static /*HDR*/
int show_lan_intf( MBG_DEV_HANDLE dh, const PCPS_DEV *p_dev, const char *info )
{
  IP4_SETTINGS ip4_settings;
  char ws[256];

  int rc = mbg_get_ip4_settings( dh, &ip4_settings );

  if ( mbg_cond_err_msg( rc, "mbg_get_ip4_settings" ) )
    return rc;

  printf( "On-board LAN interface settings:" );

  if ( ip4_settings.flags & IP4_MSK_DHCP )
    printf( "  (DHCP client)\n" );
  else
  {
    printf( "\n" );

    snprint_ip4_addr( ws, sizeof( ws ), &ip4_settings.ip_addr, NULL );
    printf( "  IP Address:     %s\n", ws );

    snprint_ip4_addr( ws, sizeof( ws ), &ip4_settings.netmask, NULL );
    printf( "  Net Mask:       %s\n", ws );

    snprint_ip4_addr( ws, sizeof( ws ), &ip4_settings.broad_addr, NULL );
    printf( "  Broadcast Addr: %s\n", ws );

    snprint_ip4_addr( ws, sizeof( ws ), &ip4_settings.gateway, NULL );
    printf( "  Gateway:        %s\n", ws );
  }

  return MBG_SUCCESS;

}  // show_lan_intf



static /*HDR*/
const char *intv_str( int i )
{
  static char s[20];

  int abs_i = abs( i );
  ulong ul;

  // Currently the valid range is [-7:+7]
  if ( abs_i > 7 )
    return str_empty;

  ul = 1UL << abs_i;

  snprintf_safe( s, sizeof( s ), " (%s%lu s)", ( i < 0 ) ? "1/" : str_empty, ul );

  return s;

}  // intv_str



static /*HDR*/
int show_ptp_cfg( MBG_DEV_HANDLE dh, const PCPS_DEV *p_dev, const char *info )
{
  ALL_PTP_CFG_INFO all_ptp_cfg_info;
  PTP_CFG_INFO *pi = &all_ptp_cfg_info.ptp_cfg_info;
  PTP_CFG_SETTINGS *ps = &pi->settings;
  char ws[256];
  int unicast_supported;
  int idx;

  int rc = mbg_get_all_ptp_cfg_info( dh, &all_ptp_cfg_info );

  if ( mbg_cond_err_msg( rc, "mbg_get_all_ptp_cfg_info" ) )
    return rc;

  unicast_supported = ( pi->supp_flags & PTP_CFG_MSK_SUPPORT_PTP_UNICAST ) != 0;

  printf( "\nPTP configuration:\n");

  idx = ps->ptp_role;
  printf( "  PTP Role        :     %s (%s)\n", _ptp_role_name_short( idx ), _ptp_role_name( idx ) );

  idx = ps->nw_prot;
  printf( "  Network Protocol:     %s (%s)\n", nw_prot_short[idx], nw_prot[idx] );

  printf( "  Delay Mechanism :     %s\n", delay_mech[ps->delay_mech] );
  printf( "  Domain Number   :     %d\n", ps->domain_number );
  printf( "  V1 HW Compat.   :     %d\n", ( ps->flags & PTP_CFG_MSK_V1_HW_COMPAT ) ? 1 : 0 );

  printf( "  Sync Msg Intv.  :    % i%s\n", ps->sync_intv, intv_str( ps->sync_intv) );
  printf( "  Ann. Msg Intv.  :    % i%s\n", ps->ann_intv, intv_str( ps->ann_intv ) );
  printf( "  Dly. Req. Intv. :    % i%s\n", ps->delay_req_intv, intv_str( ps->delay_req_intv ) );

  if ( unicast_supported )
  {
    PTP_UC_MASTER_CFG_LIMITS *p_uc_limits = &all_ptp_cfg_info.ptp_uc_master_cfg_limits;
    int i;

    for ( i = 0; i < p_uc_limits->n_supp_master; i++ )
    {
      PTP_UC_MASTER_SETTINGS *p = &all_ptp_cfg_info.all_ptp_uc_master_info_idx[i].info.settings;

      printf( "\nConfigured PTP unicast master" );

      if ( p_uc_limits->n_supp_master > 1 )
        printf( " %i", i );

      if ( ps->ptp_role == PTP_ROLE_MULTICAST_SLAVE )
        printf( " (not used for this role)" );

      printf( ":\n");

      printf( "  GM Host: %s\n", p->gm_host );

      snprint_octets( ws, sizeof( ws ), p->gm_clock_id.b, sizeof( p->gm_clock_id.b ), MAC_SEP_CHAR, NULL );
      printf( "  GM Clock ID: %s%s\n", ws,
              ( memcmp( &p->gm_clock_id, &clock_id_wildcard, sizeof( p->gm_clock_id ) ) == 0 ) ?
              str_spc_wildcard : str_empty );

      printf( "  GM Port ID: %d%s\n", p->gm_port_id,
              ( p->gm_port_id == PTP_PORT_ID_WILDCARD ) ? str_spc_wildcard : str_empty );

      printf( "  Sync Msg Intv.  :    % i%s\n", p->sync_intv, intv_str( p->sync_intv ) );
      printf( "  Ann. Msg Intv.  :    % i%s\n", p->ann_intv, intv_str( p->ann_intv ) );
      printf( "  Dly. Req. Intv. :    % i%s\n", p->delay_req_intv, intv_str( p->delay_req_intv ) );
      printf( "  Message Duration:     %i s\n", p->message_duration );
    }
  }

  return MBG_SUCCESS;

}  // show_ptp_cfg



static /*HDR*/
/**
 * @brief Lookup a string in a string table and return the table index.
 *
 * @param[in]  s          The string to be searched for in the string table.
 * @param[in]  tbl        A table of strings to be searched.
 * @param[in]  n_entries  The number of strings in the string table.
 * @param[in]  supp_mask  A string with a given index is only supported if the
 *                        corresponding bit is set in this mask.
 * @param[in]  info       A descriptive name of the parameter which is to be
 *                        set to the index of the searched string.
 *
 * @return  @b >=0 for a valid, supported table index, or<br>
 *          @b <0  in case of an unknown or unsupported parameter.
 */
int get_chk_str_table_idx( const char *s, const char *tbl[], int n_entries,
                           uint32_t supp_mask, const char *info )
{
  int i;
  const char *cp;

  for ( i = 0; i < n_entries; i++ )
  {
    cp = tbl[i];

    if ( strncmp( s, cp, strlen( cp ) ) == 0 )
      if ( supp_mask & ( 1UL << i ) )
        return i;
  }

  printf( "error: %s %s\n",
          ( i == n_entries ) ? "unknown" : "unsupported",
          info );

  return -3;

}  // get_chk_str_table_idx



static /*HDR*/
/**
 * @brief Lookup a parameter in an argument list and check if a colon is appended.
 *
 * @param[in]   arg  An argument list of the form "name:val,name:val,...".
 * @param[in]   id   A parameter name searched for in the argument list.
 * @param[out]  p    A pointer to a (char *) which is set to the beginning
 *                   of the value part of a parameter string.
 *
 * @return  ::MBG_SUCCESS on success. If parameter has been found,
 *          @p *p is set to the parameter value, else to @a NULL.
 *          ::MBG_ERR_PARM_FMT if syntax error, i.e. missing colon.
 */
int chk_parm_name( const char *arg, const char *id, char **p )
{
  char *cp = strstr( arg, id );

  if ( cp )
  {
    cp += strlen( id );

    if ( *cp != ':' )
      return MBG_ERR_PARM_FMT;

    cp++;
  }

  if ( p )
    *p = cp;  // May be NULL.

  return MBG_SUCCESS;

}  // chk_parm_name



static /*HDR*/
/**
 * @brief Lookup a parameter in an argument list and check if the value string is valid.
 *
 * This function expects that the parameter value is a known string which can
 * be found in a table of known strings. A bit mask indicates if a string with
 * a given table index is supported, or not.
 *
 * @param[in]  arg        An argument list of the form "name:val,name:val,...".
 * @param[in]  id         The name of the argument to be checked.
 * @param[in]  tbl        A table of strings with predefined parameter values.
 * @param[in]  n_entries  The number of strings in the string table.
 * @param[in]  supp_mask  A string with a given index is only supported if the
 *                        corresponding bit is set in this mask.
 * @param[in]  info       A descriptive name of the parameter which is to be
 *                        set to the index of the searched string.
 *
 * @return  @b >=0  A valid, supported table index<br>
 *          @b -1   Parameter not found<br>
 *          @b -2   Unknown or unsupported parameter, or syntax error.
 */
int chk_tbl_parm( const char *arg, const char *id, const char *tbl[],
                  int n_entries, uint32_t supp_mask, const char *info )
{
  char *cp;
  int rc = chk_parm_name( arg, id, &cp );

  if ( rc < 0 )
    return -2;

  if ( cp == NULL )
    return -1;

  rc = get_chk_str_table_idx( cp, tbl, n_entries, supp_mask, info );

  if ( rc < 0 )
    return -2;

  return rc;

}  // chk_tbl_parm



static /*HDR*/
/**
 * @brief Lookup an int16_t parameter in an argument list
 *
 * Check and save the numeric parameter if in a valid range.
 *
 * @param[in]  arg           An argument list of the form "name:val,name:val,..."
 * @param[in]  id            The name of the argument to be checked.
 * @param[in]  p             A pointer to a variable where the parameter value is
 *                           saved if valid.
 * @param[in]  range_min     The minimum allowed value for the parameter.
 * @param[in]  range_max     The maximum allowed value for the parameter.
 * @param[in]  is_supported  A flag indicating if the parameter is actually supported.
 * @param[in]  info          A descriptive name of the parameter.
 *
 * @return  @b >=0  A valid, supported table index<br>
 *          @b -1   Parameter not found, or out of range.
 */
int chk_int16_parm( const char *arg, const char *id, int16_t *p, int16_t range_min,
                    int16_t range_max, int is_supported, const char *info )
{
  char *cp;
  int idx = chk_parm_name( arg, id, &cp );

  if ( mbg_rc_is_error( idx ) )  // Parameter error.
    return idx;

  if ( cp )       // Parameter found.
  {
    if ( !is_supported )
      err_unicast_nsupp = 1;
    else
    {
      int16_t tmp = atoi( cp );

      if ( ( tmp < range_min ) || ( tmp > range_max ) )
      {
        printf( "error: %s %i out of range (%i..%i)\n", info, tmp, range_min, range_max );
        return MBG_ERR_RANGE;
      }

      *p = tmp;
      printf( "  setting %s: %i\n", info, tmp );
    }
  }

  return 0;

}  // chk_int16_parm



static /*HDR*/
int set_ptp_cfg( MBG_DEV_HANDLE dh, const char *arg, const PCPS_DEV *p_dev )
{
  ALL_PTP_CFG_INFO all_ptp_cfg_info = { { { 0 } } };
  ALL_PTP_CFG_INFO prv_all_ptp_cfg_info;
  PTP_CFG_INFO *p_info;
  PTP_CFG_SETTINGS *p_settings;
  PTP_UC_MASTER_CFG_LIMITS *p_uc_limits;
  PTP_UC_MASTER_INFO *p_uc_info;
  PTP_UC_MASTER_SETTINGS *p_uc_settings;
  uint32_t supp_mask;
  IP4_ADDR ip4addr;
  char ws[256];
  char *cp;
  int idx;
  int unicast_supported;
  int uc_master_idx = 0;
  const char *err_info = NULL;
  int rc = mbg_get_all_ptp_cfg_info( dh, &all_ptp_cfg_info );

  if ( mbg_rc_is_error( rc ) )
    return rc;  // Failed to read current settings and capabilities.


  err_unicast_nsupp = 0;

  // Save a copy of the current settings.
  prv_all_ptp_cfg_info = all_ptp_cfg_info;

  p_info = &all_ptp_cfg_info.ptp_cfg_info;
  p_settings = &p_info->settings;
  unicast_supported = ( p_info->supp_flags & PTP_CFG_MSK_SUPPORT_PTP_UNICAST ) != 0;

  p_uc_limits = &all_ptp_cfg_info.ptp_uc_master_cfg_limits;
  // The pointers below need to be updated whenever uc_master_idx is changed.
  p_uc_info = &all_ptp_cfg_info.all_ptp_uc_master_info_idx[uc_master_idx].info;
  p_uc_settings = &p_uc_info->settings;


  // Network protocol.
  idx = chk_tbl_parm( arg, ptp_name_net, nw_prot_short, N_PTP_NW_PROT, p_info->supp_nw_prot, "network protocol type" );

  if ( idx >= 0 )    // Valid parameter found.
    p_settings->nw_prot = idx;
  else
    if ( idx < -1 )
    {
      err_info = ptp_name_net;
      goto fail;
    }

  // Delay Mechanism.
  idx = chk_tbl_parm( arg, ptp_name_del, delay_mech, N_PTP_DELAY_MECH, p_info->supp_delay_mech, "delay mechanism" );

  if ( idx >= 0 )    // Valid parameter found.
    p_settings->delay_mech = idx;
  else
    if ( idx < -1 )
    {
      err_info = ptp_name_del;
      goto fail;
    }


  // Domain Number
  idx = chk_parm_name( arg, ptp_name_dom, &cp );

  if ( mbg_rc_is_error( idx ) )  // Parameter error.
  {
    err_info = ptp_name_dom;
    goto fail;
  }

  if ( cp )       // Parameter found.
  {
    idx = atoi( cp );
    // TODO Must check range!!
    p_settings->domain_number = idx;
  }


  // V1 Hardware compatibility flag
  idx = chk_parm_name( arg, ptp_name_v1, &cp );

  if ( mbg_rc_is_error( idx ) )  // Parameter error.
  {
    err_info = ptp_name_v1;
    goto fail;
  }

  if ( cp )       // Parameter found.
  {
    idx = atoi( cp );

    switch ( idx )
    {
      case 0:
        p_settings->flags &= ~PTP_CFG_MSK_V1_HW_COMPAT;
        break;

      case 1:
        p_settings->flags |= PTP_CFG_MSK_V1_HW_COMPAT;
        break;

      default:
        printf( "error: No valid V1 HWC settings!\n" );
        goto fail;
    }
  }


  //---- unicast stuff ----

  // PTP role.
  supp_mask = get_supp_ptp_role_mask( p_info->supp_flags );
  idx = chk_tbl_parm( arg, ptp_name_role, ptp_roles_short, N_PTP_ROLES, supp_mask, "PTP role" );

  if ( idx >= 0 )  // Valid parameter found.
  {
    if ( !unicast_supported )
      err_unicast_nsupp = 1;
    else
      p_settings->ptp_role = idx;
  }
  else
    if ( idx < -1 )  // Parameter error.
    {
      err_info = ptp_name_role;
      goto fail;
    }


  // GM Host.
  idx = chk_parm_name( arg, ptp_name_gmip, &cp );

  if ( mbg_rc_is_error( idx ) )  // Parameter error.
  {
    err_info = ptp_name_gmip;
    goto fail;
  }

  if ( cp )       // Parameter found.
  {
    if ( !unicast_supported )
      err_unicast_nsupp = 1;
    else
    {
      // Currently, only IP addresses are accepted, so check for
      // a valid IPv4 address.
      if ( str_to_ip4_addr( &ip4addr, cp ) > 0 )
      {
        snprint_ip4_addr( ws, sizeof( ws ), &ip4addr, NULL );
        printf( "  GM IP Address: %s\n", ws );

        memset( p_uc_settings->gm_host, 0, sizeof( p_uc_settings->gm_host ) );
        strcpy( p_uc_settings->gm_host, ws );
      }
      else
      {
        err_info = ptp_name_gmip;
        goto fail;
      }
    }
  }


  // GM Clock ID.
  idx = chk_parm_name( arg, ptp_name_gmid, &cp );

  if ( mbg_rc_is_error( idx ) )  // Parameter error.
  {
    err_info = ptp_name_gmid;
    goto fail;
  }

  if ( cp )       // Parameter found.
  {
    if ( !unicast_supported )
      err_unicast_nsupp = 1;
    else
    {
      PTP_CLOCK_ID gm_clock_id;

      // Check if specified GM ID is wildcard.
      if ( *cp == '*' )  // TODO Check if next char is a separator.
      {
        gm_clock_id = clock_id_wildcard;
        idx = sizeof( gm_clock_id );
      }
      else
        idx = str_to_octets( gm_clock_id.b, sizeof( gm_clock_id.b ), cp );

      if ( idx != sizeof( gm_clock_id ) )
      {
        printf( "Syntax error in specified GM clock ID\n" );
        goto fail;
      }

      p_uc_settings->gm_clock_id = gm_clock_id;

      snprint_octets( ws, sizeof( ws ), p_uc_settings->gm_clock_id.b,
           sizeof( p_uc_settings->gm_clock_id.b ), MAC_SEP_CHAR, NULL );
      printf( "  setting GM Clock ID: %s\n", ws );
    }
  }


  // GM Target Port ID.
  idx = chk_parm_name( arg, ptp_name_pid, &cp );

  if ( mbg_rc_is_error( idx ) )  // Parameter error.
  {
    err_info = ptp_name_pid;
    goto fail;
  }

  if ( cp )       // Parameter found.
  {
    if ( !unicast_supported )
      err_unicast_nsupp = 1;
    else
    {
      // Check if specified Port ID is wildcard.
      if ( *cp == '*' )  // TODO Check if next char is separator.
        p_uc_settings->gm_port_id = PTP_PORT_ID_WILDCARD;
      else
        p_uc_settings->gm_port_id = (PTP_PORT_ID) strtoul( cp, NULL, 0 );

      printf( "  setting GM port id: %d%s\n", p_uc_settings->gm_port_id,
              ( p_uc_settings->gm_port_id == PTP_PORT_ID_WILDCARD ) ? str_spc_wildcard : str_empty );
    }
  }


  // Sync Message Rate.
  idx = chk_int16_parm( arg, ptp_name_smi,
                        ( p_settings->ptp_role == PTP_ROLE_MULTICAST_SLAVE ) ?
                        &p_settings->sync_intv : &p_uc_settings->sync_intv,
                        p_uc_limits->sync_intv_min, p_uc_limits->sync_intv_max,
                        1, "sync intv." );
  if ( idx < 0 )
  {
    err_info = ptp_name_smi;
    goto fail;
  }


  // Announce Message Rate.
  idx = chk_int16_parm( arg, ptp_name_ami,
                        ( p_settings->ptp_role == PTP_ROLE_MULTICAST_SLAVE ) ?
                        &p_settings->ann_intv : &p_uc_settings->ann_intv,
                        p_uc_limits->ann_intv_min, p_uc_limits->ann_intv_max,
                        1, "ann. intv." );
  if ( idx < 0 )
  {
    err_info = ptp_name_ami;
    goto fail;
  }


  // Delay Request Interval Rate.
  idx = chk_int16_parm( arg, ptp_name_dri,
                        ( p_settings->ptp_role == PTP_ROLE_MULTICAST_SLAVE ) ?
                        &p_settings->delay_req_intv : &p_uc_settings->delay_req_intv,
                        p_uc_limits->delay_req_intv_min, p_uc_limits->delay_req_intv_max,
                        1, "delay req. intv." );
  if ( idx < 0 )
  {
    err_info = ptp_name_dri;
    goto fail;
  }



  // Message Duration.
  idx = chk_int16_parm( arg, ptp_name_dur, (int16_t *) &p_uc_settings->message_duration,
                        PTP_UC_MSG_DURATION_MIN, PTP_UC_MSG_DURATION_MAX,
                        unicast_supported, "msg. duration" );
  if ( idx < 0 )
  {
    err_info = ptp_name_dur;
    goto fail;
  }


  if ( memcmp( &all_ptp_cfg_info, &prv_all_ptp_cfg_info, sizeof( all_ptp_cfg_info ) ) != 0 )
  {
    rc = mbg_save_all_ptp_cfg_info( dh, &all_ptp_cfg_info );

    if ( mbg_cond_err_msg( rc, "mbg_save_all_ptp_cfg_info" ) )
      return rc;
  }

  return MBG_SUCCESS;


fail:
  printf( "Invalid parameter in argument" );

  if ( err_info )
    printf( " %s", err_info );

  printf( "!\n" );

  return MBG_ERR_CFG;

} // set_ptp_cfg



static /*HDR*/
int ip4_check_parm( const char *s, IP4_INFO *p )
{
  size_t l = strlen( p->name );
  int n;

  if ( strncmp( s, p->name, l ) != 0 )
    return 0;  // Parameter does not match.

  if ( s[l] != ':' )
    goto fail;  // Parameter syntax error: name not followed by colon.

  l++;

  n = str_to_ip4_addr( p->addr, &s[l] );

  if ( n < 0 )
    goto fail;  // Parameter syntax error: failed to convert numeric address.

  l += n;

  return _int_from_size_t( l );

fail:
  return MBG_ERR_CFG;

}  // ip4_check_parm



static /*HDR*/
int set_lan_intf( MBG_DEV_HANDLE dh, const char *arg, const PCPS_DEV *p_dev )
{
  IP4_SETTINGS prv_ip4_settings;
  IP4_SETTINGS ip4_settings = { 0 };
  IP4_ADDR default_broad_addr;

  IP4_INFO ip4_info[N_IP4_INFO] =
  {
    { ip4_name_ip, &ip4_settings.ip_addr },
    { ip4_name_nm, &ip4_settings.netmask },
    { ip4_name_ba, &ip4_settings.broad_addr },
    { ip4_name_gw, &ip4_settings.gateway }
  };

  int rc = mbg_get_ip4_settings( dh, &prv_ip4_settings );

  if ( mbg_cond_err_msg( rc, "mbg_get_ip4_settings" ) )
    return rc;

  if ( strcmp( arg, "DHCP" ) == 0 )
  {
    ip4_settings = prv_ip4_settings;
    ip4_settings.flags |= IP4_MSK_DHCP;
    goto save;
  }

  for (;;)
  {
    int i;

    for ( i = 0; i < N_IP4_INFO; i++ )
    {
      rc = ip4_check_parm( arg, &ip4_info[i] );

      if ( rc == 0 ) // Check next.
        continue;

      if ( rc < 0 )  // Error.
        goto invalid_msg;

      arg += rc;

      if ( *arg == 0 )  // End of parameter string.
        goto done;

      if ( *arg != ',' )
        goto invalid_msg;

      arg++;
    }
  }


done:  // Now check static configuration.
  if ( ip4_settings.ip_addr == 0 )  // No IP address specified on the command line.
    ip4_settings.ip_addr = prv_ip4_settings.ip_addr;  // Use previous IP address.

  if ( ip4_settings.ip_addr == 0 )  // No IP address specified at all.
  {
    printf( "*** Aborting: No IP address specified\n" );
    goto invalid;
  }

  if ( ip4_settings.netmask == 0 )  // No network mask specified on the command line.
    ip4_settings.netmask = prv_ip4_settings.netmask;  // Use previous network mask.

  if ( ip4_settings.netmask == 0 )  // No network mask specified at all.
  {
    printf( "*** Aborting: No network mask specified\n" );
    goto invalid;
  }

  // The default broadcast address is computed from the IP address and the network mask.
  default_broad_addr = ip4_settings.ip_addr | ~ip4_settings.netmask;

  if ( ip4_settings.broad_addr == 0 )  // No broadcast address specified on the command line.
    ip4_settings.broad_addr = default_broad_addr;
  else
    if ( ip4_settings.broad_addr != default_broad_addr )
    {
      char ws1[40];
      char ws2[40];
      snprint_ip4_addr( ws1, sizeof( ws1 ), &ip4_settings.broad_addr, NULL );
      snprint_ip4_addr( ws2, sizeof( ws2 ), &default_broad_addr, NULL );
      printf( "*** Warning: Broadcast address %s does not match the default broadcast address %s\n",
              ws1, ws2 );
    }

  if ( ip4_settings.gateway == 0 )
    ip4_settings.gateway = prv_ip4_settings.gateway;

  ip4_settings.flags = prv_ip4_settings.flags & ~IP4_MSK_DHCP;
  // Fall through to save:

save:
  rc = mbg_set_ip4_settings( dh, &ip4_settings );

  if ( mbg_cond_err_msg( rc, "mbg_set_ip4_settings" ) )
    return rc;

  return MBG_SUCCESS;


invalid_msg:
  printf( "*** Warning: invalid LAN interface parameter syntax\n" );
  // Fall through to invalid:

invalid:
  return MBG_ERR_CFG;  // Invalid parameter or parameter syntax error.

}  // set_lan_intf



static /*HDR*/
int set_gps_pos( MBG_DEV_HANDLE dh, const char *gp )
{
  LLA new_pos_lla;
  char *cp;
  int rc;
  double r2d = 180 / PI;

  new_pos_lla[LAT] = strtod( gp, &cp ) / r2d;

  if ( *cp++ != ',' )
    goto invalid;

  new_pos_lla[LON] = strtod( cp, &cp ) / r2d;

  if ( *cp++ != ',' )
    goto invalid;

  new_pos_lla[ALT] = strtod( cp, &cp );

  if (
        ( ( new_pos_lla[LAT] * r2d ) < -90 ) ||
        ( ( new_pos_lla[LAT] * r2d ) > +90 ) ||
        ( ( new_pos_lla[LON] * r2d ) < -180 ) ||
        ( ( new_pos_lla[LON] * r2d ) > +180 ) ||
        ( new_pos_lla[ALT] < -50   ) ||
        ( new_pos_lla[ALT] > 20000 )
     )
    goto invalid;


  rc = mbg_set_gps_pos_lla ( dh, new_pos_lla );

  if ( mbg_cond_err_msg( rc, "mbg_set_gps_pos_lla" ) )
    return rc;

  printf( "The receiver position of the device has been set to lat=%+.4f, lon=%+.4f, alt=%.0fm\n",
          new_pos_lla[LAT] * r2d, new_pos_lla[LON] * r2d, new_pos_lla[ALT] );

  return rc;


invalid:
  fprintf( stderr, "** Invalid GPS position parameters: %s\n", gp );

  return MBG_ERR_CFG;

}  // set_gps_pos



static /*HDR*/
int set_date_time( MBG_DEV_HANDLE dh, const PCPS_DEV *p_dev,
                   const char *sdate, const char *stime )
{
  PCPS_TIME_UNION u = { { 0 } };
  TTM ttm = { 0 };
  unsigned int year = 0;
  unsigned int month = 0;
  unsigned int mday = 0;
  unsigned int hour = 0;
  unsigned int min = 0;
  unsigned int sec = 0;
  unsigned int sec100 = 0;
  int rc;

  // Either a date string, a time string, or both
  // may have been passed to this function.
  // If either of them is NULL, read the current date/time
  // as default values.
  if ( sdate == NULL || stime == NULL )
  {
    rc = mbg_get_time( dh, &u.t );

    if ( mbg_cond_err_msg( rc, "mbg_get_time" ) )
      return rc;
  }


  if ( sdate )
  {
    rc = sscanf( sdate, "%u-%u-%u", &year, &month, &mday );

    if ( ( rc < 3 )
      || ( month < 1 ) || ( month > 12 )
      || ( mday < 1 ) || ( mday > 31 ) )
    {
      printf( "** Invalid date: %04u-%02u-%02u\n", year, month, mday );
      return MBG_ERR_CFG;
    }
  }


  if ( stime )
  {
    rc = sscanf( stime, "%u:%u:%u.%u", &hour, &min, &sec, &sec100 );

    if ( ( rc < 2 )     // At least hours and minutes are required.
      || ( hour > 23 )
      || ( min  > 59 )
      || ( sec > 60 )
      || ( sec100 > 99 ) )
    {
      printf( "** Invalid time: %02u:%02u:%02u.%02u\n", hour, min, sec, sec100 );
      return MBG_ERR_CFG;
    }
  }

  // GPS and non-GPS devices require different API calls that require
  // different structures to set the on-board date and time,
  // so we have to distinguish.

  if ( _pcps_is_gps( p_dev ) )  // Is a GPS card.
  {
    ttm.channel = -1;

    if ( sdate )  // New date.
    {
      ttm.tm.year = year;
      ttm.tm.month = month;
      ttm.tm.mday = mday;
    }
    else  // Copy current date as default.
    {
      ttm.tm.year = u.t.year + 2000;
      ttm.tm.month = u.t.month;
      ttm.tm.mday = u.t.mday;
    }

    if ( stime )  // New time.
    {
      ttm.tm.hour = hour;
      ttm.tm.min = min;
      ttm.tm.sec = sec;
      ttm.tm.frac = sec100;
    }
    else  // Copy current time as default.
    {
      ttm.tm.hour = u.t.hour;
      ttm.tm.min = u.t.min;
      ttm.tm.sec = u.t.sec;
      ttm.tm.frac = u.t.sec100;
    }

    ttm.tm.frac *= 100000;  // Fractions are in 100 ns units.

    #if 0
      // Existing versions of the GPS devices just take
      // TTM.tm as local time without accounting for
      // the status flags, or UTC offset.
      // Instead, the TTM.tm time is converted on-board
      // to UTC depending on the local TZDL configuration.
      // This works if the system time and the
      ttm.tm.offs_from_utc = 7200;
      ttm.tm.status |= TM_UTC | TM_LOCAL;
      ttm.tm.status |= TM_DL_ENB;
    #endif

    rc = mbg_set_gps_time( dh, &ttm );

    if ( mbg_cond_err_msg( rc, "mbg_set_gps_time" ) )
      return rc;
  }
  else   // Is not a GPS card.
  {
    if ( sdate )  // New date.
    {
      // Determine the day-of-week for the given date.
      struct tm tm = { 0 };

      tm.tm_year = year - 1900;
      tm.tm_mon = month - 1;
      tm.tm_mday = mday;
      tm.tm_hour = 12;
      tm.tm_isdst = -1;
      mktime( &tm );

      u.stime.year = year % 100;
      u.stime.month = month;
      u.stime.mday = mday;
      u.stime.wday = _wday_sun06_to_mon17( tm.tm_wday );
    }

    if ( stime )  // New time.
    {
      u.stime.hour = hour;
      u.stime.min = min;
      u.stime.sec = sec;
      u.stime.sec100 = sec100;
    }

    if ( u.stime.wday == 0 )
      u.stime.wday = 1;        // Dummy.

    rc = mbg_set_time( dh, &u.stime );

    if ( mbg_cond_err_msg( rc, "mbg_set_time" ) )
      return rc;
  }

  printf( "Device date/time have been set.\n" );

  return MBG_SUCCESS;

}  // set_date_time



static /*HDR*/
int check_setup_receiver_info( MBG_DEV_HANDLE dh, RECEIVER_INFO *p_ri )
{
  int rc = MBG_SUCCESS;

  // Set up the RECEIVER_INFO structure only if this has not been done
  // before. Check the ticks_per_sec field to see if the structure
  // has already been set up, or not.
  if ( p_ri->ticks_per_sec == 0 && p_ri->model_code == 0 )
  {
    rc = mbg_setup_receiver_info( dh, NULL, p_ri );
    mbg_cond_err_msg( rc, "mbg_setup_receiver_info" );
  }

  return rc;

}  // check_setup_receiver_info



static /*HDR*/
/**
 * @brief Read all configuration info of the onboard serial ports.
 *
 * Check and set up the ::RECEIVER_INFO first, if required.
 *
 * @param[in]      dh       Valid ::MBG_DEV_HANDLE handle to a Meinberg device.
 * @param[out]     p_rpcfg  Address of a ::RECEIVER_PORT_CFG structure to be set up.
 * @param[in]      p_dev    Address of a ::PCPS_DEV structure associated with the device.
 * @param[in,out]  p_ri     Address of a ::RECEIVER_INFO associated with the device,
 *                          set up first, if required.
 *
 * @return The (positive) number of onboard COM ports on success,
 *         or one of the (negative) @ref MBG_ERROR_CODES on error.
 */
int check_get_receiver_port_cfg( MBG_DEV_HANDLE dh, RECEIVER_PORT_CFG *p_rpcfg,
                                 const PCPS_DEV *p_dev, RECEIVER_INFO *p_ri )
{
  int rc = check_setup_receiver_info( dh, p_ri );

  if ( mbg_rc_is_error( rc ) )
    goto out;

  // Set up the RECEIVER_PORT_CFG structure only if this has not been done
  // before. Check whether the number of ports is > 0 and the first port's
  // baud rate is still 0 to see if the structure has already been set up.
  if ( ( p_ri->n_com_ports > 0 ) &&
       ( p_rpcfg->pii[0].port_info.port_settings.parm.baud_rate == 0 ) )
  {
    rc = mbg_get_serial_settings( dh, p_dev, p_rpcfg, p_ri );
    mbg_cond_err_msg( rc, "mbg_get_serial_settings" );
  }

  if ( mbg_rc_is_success( rc ) )
    rc = p_ri->n_com_ports;

out:
  return rc;

}  // check_get_receiver_port_cfg



static /*HDR*/
int snprint_port_cfg( char *s, int sz, unsigned int port_num,
                      const RECEIVER_PORT_CFG *p_rpcfg )
{
  const PORT_SETTINGS *p_ps = &p_rpcfg->pii[port_num].port_info.port_settings;

  int n = snprintf( s, sz, "\"%s\" %s at %lu/%s",
                    p_rpcfg->stii[p_ps->str_type].str_type_info.long_name,
                    mode_names[p_ps->mode],
                    (unsigned long) p_ps->parm.baud_rate,
                    p_ps->parm.framing
                  );

  return n;

}  // snprint_port_cfg



static /*HDR*/
void show_serial_settings( MBG_DEV_HANDLE dh, const RECEIVER_PORT_CFG *p_rpcfg,
                           const RECEIVER_INFO *p_ri )
{
  char ws[256];
  unsigned int i;

  for ( i = 0; i < p_ri->n_com_ports; i ++ )
  {
    snprint_port_cfg( ws, sizeof( ws ), i, p_rpcfg );
    printf( "Serial port COM%u: %s.\n", i, ws );
  }

}  // show_serial_settings



static /*HDR*/
void print_port_info_errors( const char *port_name, unsigned int port_num,
                                   int flags, const RECEIVER_PORT_CFG *p_rpcfg )
{
  const char *msg_nsupp_drvr = "is not supported by the driver software";

  const PORT_INFO *p_pi = &p_rpcfg->pii[port_num].port_info;
  const PORT_SETTINGS *p_ps = &p_pi->port_settings;


  if ( flags & MBG_PS_MSK_BAUD_RATE_OVR_SW )
    printf( "** Baud rate %lu %s.\n", (ulong) p_ps->parm.baud_rate, msg_nsupp_drvr );
  else
    if ( flags & MBG_PS_MSK_BAUD_RATE )
      printf( "** Baud rate %lu is not supported by %s%u.\n",
              (ulong) p_ps->parm.baud_rate, port_name, port_num );


  if ( flags & MBG_PS_MSK_FRAMING_OVR_SW )
    printf( "** Framing %s %s.\n", p_ps->parm.framing, msg_nsupp_drvr );
  else
    if ( flags & MBG_PS_MSK_FRAMING )
      printf( "** Framing %s is not supported by %s%u.\n",
              p_ps->parm.framing, port_name, port_num );


  if ( flags & MBG_PS_MSK_HS_OVR_SW )
    printf( "** Handshake mode %u %s.\n", p_ps->parm.handshake, msg_nsupp_drvr );
  else
    if ( flags & MBG_PS_MSK_HS )
      printf( "** Handshake mode %u is not supported by %s%u.\n",
              (unsigned int) p_ps->parm.handshake, port_name, port_num );


  if ( flags & MBG_PS_MSK_STR_TYPE_OVR_DEV )
    printf( "** String type index %u exceeds number of string types supp. by device.\n",
            p_ps->str_type );
  else
    if ( flags & MBG_PS_MSK_STR_TYPE )
      printf( "** String type \"%s\" is not supported by %s%u.\n",
              p_rpcfg->stii[p_ps->str_type].str_type_info.long_name,
              port_name, port_num );


  if ( flags & MBG_PS_MSK_STR_MODE_OVR_SW )
      printf( "** String mode index %u exceeds number of string modes supported by driver software (%u).\n",
              p_ps->mode, N_STR_MODE );
  else
    if ( flags & MBG_PS_MSK_STR_MODE )
      printf( "** String mode \"%s\" is not supported by string type \"%s\" via %s%u .\n",
              mode_names[p_ps->mode],
              p_rpcfg->stii[p_ps->str_type].str_type_info.long_name,
              port_name, port_num );

}  // print_port_info_errors



static /*HDR*/
int save_serial_settings( MBG_DEV_HANDLE dh, unsigned int port_num, const char *parm_str,
                          const PCPS_DEV *p_dev, const RECEIVER_INFO *p_ri )
{
  char ws[256];
  RECEIVER_PORT_CFG rpcfg = { { { 0 } } };
  PORT_INFO *p_pi = &rpcfg.pii[port_num].port_info;
  PORT_SETTINGS *p_ps = &p_pi->port_settings;
  ulong ul;
  const char *cp;
  char *p_tail;
  int rc;
  int flags;
  int i;

  // Load current settings and supported settings.
  rc = mbg_get_serial_settings( dh, p_dev, &rpcfg, p_ri );

  if ( mbg_cond_err_msg( rc, "mbg_get_serial_settings" ) )
    return rc;


  cp = parm_str;
  p_ps->parm.baud_rate = strtoul( cp, &p_tail, 10 );

  if ( p_tail == cp )  // No number found.
    goto invalid;

  cp = p_tail;

  if ( *cp++ != ',' )  // Separator before framing missing.
    goto invalid;

  for ( i = 0; i < sizeof( p_ps->parm.framing ); i++ )
  {
    int c = *cp;

    if ( !isalnum( c ) )    // Stop copying if non-alpha and non-digit.
      break;

    p_ps->parm.framing[i] = *cp++;
  }

  p_ps->parm.framing[i] = 0;  // Force terminating 0.

  p_ps->parm.handshake = HS_NONE;  // This is the only supported setting.


  // Get optional string type index.

  if ( *cp++ != ',' )
    goto done_parm_str;

  ul = strtoul( cp, &p_tail, 10 );

  if ( p_tail != cp )
    p_ps->str_type = (uint8_t) ul;  // TODO check range ?

  cp = p_tail;


  // Get optional string mode index.

  if ( *cp++ != ',' )
    goto done_parm_str;

  ul = strtoul( cp, &p_tail, 10 );

  if ( p_tail != cp )
    p_ps->mode = (uint8_t) ul;  // TODO check range ?


done_parm_str:

  // Check if the new parameter set is valid.
  flags = check_valid_port_info( p_pi, rpcfg.stii, p_ri->n_str_type );

  if ( flags )  // Parameters not valid.
  {
    print_port_info_errors( "COM", port_num, flags, &rpcfg );
    goto invalid;
  }

  // Save new parameters.
  rc = mbg_save_serial_settings( dh, p_dev, &rpcfg, port_num );

  if ( mbg_cond_err_msg( rc, "mbg_save_serial_settings" ) )
    return rc;


  snprint_port_cfg( ws, sizeof( ws ), port_num, &rpcfg );
  printf( "The COM%u port of the device has been set to %s.\n", port_num, ws );

  return MBG_SUCCESS;


invalid:
  fprintf( stderr, "** Invalid COM port parameters: %s\n", parm_str );
  return MBG_ERR_CFG;

}  // save_serial_settings



static /*HDR*/
/**
 * @brief Read all configuration info of the onboard programmable pulse outputs.
 *
 * Check and set up the ::RECEIVER_INFO first, if required.
 *
 * @param[in]      dh    Valid ::MBG_DEV_HANDLE handle to a Meinberg device.
 * @param[out]     api   Address of an array of ::ALL_POUT_INFO_IDX structures to be set up.
 * @param[in,out]  p_ri  Address of a ::RECEIVER_INFO associated with the device,
 *                       set up first, if required.
 *
 * @return The (positive) number of supported programmable pulse outputs on success,
 *         or one of the (negative) @ref MBG_ERROR_CODES on error.
 */
int check_get_pout_cfg( MBG_DEV_HANDLE dh, ALL_POUT_INFO_IDX api, RECEIVER_INFO *p_ri )
{
  int rc = check_setup_receiver_info( dh, p_ri );

  // Set up the ALL_POUT_INFO_IDX structure only if this has not been done
  // before. Check whether the number of ports is > 0 and the baud rate of the
  // first port is still 0 to see if the structure has already been set up.
  if ( ( p_ri->n_prg_out > 0 ) &&
       ( api[0].pout_info.supp_modes == 0 ) )
  {
    rc = mbg_get_gps_all_pout_info( dh, api, p_ri );
    mbg_cond_err_msg( rc, "mbg_get_gps_all_pout_info" );
  }

  if ( mbg_rc_is_success( rc ) )
    rc = p_ri->n_prg_out;

  return rc;

}  // check_get_pout_cfg



static /*HDR*/
int help_pout_arg( MBG_DEV_HANDLE dh, const PCPS_DEV *p_dev,
                   const OPT_HANDLER_SPEC *p_opt, CTRL_FLAGS ctrl_flags )
{
  const INDENTS *p_ind = &usage_indents;
  const INDENTS *p_ind_detailed = &usage_indents_detailed;
  int rc = MBG_SUCCESS;
  int i;

  usage_line( p_ind, p_opt, NULL, "Show settings of the programmable output(s)" );
  usage_line( p_ind, p_opt, "MODE:<m>[,LEN:<l>][,INV:<i>][,OIS:<o>][,SHIFT:<s>]", " Configure programmable output <n>" );  // TODO Fix indentation.

  printf( "\n"
          "  where:\n" );

  printf( "    MODE:<m>   Specifies the programmable output mode with index <m>, see mbgctrl -?.\n"
          "               Please note that subsequent parameters may only be appropriate for specific modes.\n\n" );

  printf( "    LEN:<l>    Specifies the pulse lenght for modes that support this.\n"
          "               <l> is an integer value in 10 ms units, i.e. <l> = 20 yields 200 ms.\n\n" );

  printf( "    INV:<i>    \"Inverted\" flag specifying if the output level is to be inverted,\n"
          "               if the output supports this.\n"
          "               Values for <i>: 1 invert output level, 0 don't invert.\n\n" );

  printf( "    OIS:<o>    \"Only If Sync\" flag specifying if the output is to be enabled ONLY\n"
          "               while the device is synchronized, if the output supports this.\n"
          "               Values for <o>: 1 enable this feature, 0 disable this feature\n"
          "               NOTE: This overrides the Enable Flags settings (parameter \"EF\").\n"
          "               The output is enabled ONLY when the device state changes to \"synchronized\"\n"
          "               after power-up, and is disabled again when the device enters holdover mode,\n"
          "               i.e. the reference signal is lost.\n\n" );

  printf( "    SHIFT:<s>  Specifies a phase shift of the output slope, if the output supports this.\n"
          "               <s> is an integer value, in nanoseconds.\n"
          "               The maximum range is %+li to %+li ns,\n"
          "               corresponding to %+li to %+li ms.\n"
          "               The effective resolution depends on the resolution of the internal clock\n"
          "               of the device, which may be e.g. 10 or 20 ns, depending on the device type.\n"
          "               See mbgctrl -?.\n\n",
          (long) DEFAULT_POUT_PULSE_SHIFT_MIN, (long) DEFAULT_POUT_PULSE_SHIFT_MAX,
          (long) DEFAULT_POUT_PULSE_SHIFT_MIN / 1000L, (long) DEFAULT_POUT_PULSE_SHIFT_MAX / 1000L );


  if ( dh != MBG_INVALID_DEV_HANDLE )
  {
    RECEIVER_INFO ri = { 0 };
    ALL_POUT_INFO_IDX api = { { 0 } };
    int n_pout;

    rc = check_get_pout_cfg( dh, api, &ri );

    if ( mbg_rc_is_error( rc ) )
      goto out;

    n_pout = rc;

    for ( i = 0; i < n_pout; i++ )
    {
      const POUT_INFO *pi = &api[i].pout_info;

      printf( "%*s", p_ind->indent_2, str_empty );
      printf( "Programmable output %i:\n", i );

      print_bit_mask_list( "Supported modes", NULL, pi->supp_modes,
                           N_POUT_MODES, pout_mode_names_eng, NULL, 0,
                           ctrl_flags | CTRL_PRINT_IDX, p_ind_detailed );

      // TODO Evaluate more properties.
      usage_note( p_ind_detailed->indent_2, "Output level can%s be inverted.",
                  ( pi->flags & POUT_NOT_INVERTIBLE ) ? str_spc_not : str_empty );

      if ( pi->flags & POUT_FIXED_PULSE_LEN )
        usage_note( p_ind_detailed->indent_2, "Pulse length is fixed and can't be changed." );

      if ( pi->flags & POUT_SUPP_PULSE_SHIFT )
        usage_note( p_ind_detailed->indent_2, "Output supports pulse shift with resolution %u ns.",
                    pi->pulse_shift_res );

      printf( "\n" );
    }
  }
  else
  {
#if 0 // ### TODO
    print_bit_mask_list( "modes", str_supp_by_dev, tsi.supp_scales,
                         N_MBG_TIME_SCALE, time_scale_names, NULL, ctrl_flags | CTRL_PRINT_IDX );
#endif
  }

out:
  return rc;

}  // help_pout_arg



static /*HDR*/
int eval_pout( MBG_DEV_HANDLE dh, const char *s, int inst_num )
{
  RECEIVER_INFO ri = { 0 };
  ALL_POUT_INFO_IDX api = { { 0 } };
  ALL_POUT_INFO_IDX prv_api;
  POUT_INFO *p_pi = &api[inst_num].pout_info;  // TODO check inst_num range?
  POUT_SETTINGS *p_ps = &p_pi->pout_settings;
  const char *err_info = NULL;
  char *cp;
  int n_pout;
  int idx;
  int i;
  int rc = check_get_pout_cfg( dh, api, &ri );

  if ( mbg_cond_err_msg( rc, "check_get_pout_cfg" ) )
    return rc;

  n_pout = rc;  // Now contains the number of programmable pulse outputs.

  // save current settings
  memcpy( prv_api, api, sizeof( prv_api ) );

  // Mode
  idx = chk_parm_name( s, pout_name_mode, &cp );

  if ( mbg_rc_is_error( idx ) )  // Parameter error.
  {
    err_info = pout_name_mode;
    goto fail;
  }

  if ( cp )       // Parameter found.
  {
    idx = atoi( cp );

    if ( idx < 0 || idx >= N_POUT_MODES )
    {
      printf( "Programmable output mode %i out of range (0..%i)\n", idx, N_POUT_MODES - 1 );
      goto fail;
    }

    if ( !_is_supported( idx, p_pi->supp_modes ) )
    {
      printf( "Programmable output mode %i (%s) not supported for output %i\n",
              idx, _get_pout_mode_name( idx ), inst_num );
      goto fail;
    }

    p_ps->mode = idx;
    printf( "Programmable output mode for output %i changed to %s (%i)\n",
            inst_num, _get_pout_mode_name( p_ps->mode ), p_ps->mode );
  }


  // Pulse len
  idx = chk_parm_name( s, pout_name_len, &cp );

  if ( mbg_rc_is_error( idx ) )  // Parameter error.
  {
    err_info = pout_name_len;
    goto fail;
  }

  if ( cp )       // Parameter found.
  {
    idx = atoi( cp );

    if ( !_is_supported( p_ps->mode, POUT_MODES_MODE_PARAM_AS_PULSE_LEN ) )
    {
      printf( "Pulse length parameter not supported for mode \"%s\"\n",
              _get_pout_mode_name( p_ps->mode ) );
      goto fail;
    }

    if ( idx < 0 || idx >= MAX_POUT_PULSE_LEN )
    {
      printf( "Pulse length %i out of range (1..%i)\n", idx, MAX_POUT_PULSE_LEN );
      goto fail;
    }

    if ( p_pi->flags & POUT_FIXED_PULSE_LEN )
    {
      if ( idx != p_ps->mode_param )
        printf( "Warning. pulse length %i (%i ms) is fix and can't be changed!\n",
                p_ps->mode_param, p_ps->mode_param * 10 );
    }
    else
    {
      p_ps->mode_param = idx;
      printf( "Pulse length for programmable output %i changed to %i (%i ms)\n",
              inst_num, p_ps->mode_param, p_ps->mode_param * 10 );
    }
  }


  // "Inverted" flag.
  idx = chk_parm_name( s, pout_name_inv, &cp );

  if ( mbg_rc_is_error( idx ) )  // Parameter error.
  {
    err_info = pout_name_inv;
    goto fail;
  }

  if ( cp )       // Parameter found.
  {
    idx = atoi( cp );

    if ( idx < 0 || idx > 1 )
    {
      printf( "Invalid flag value %i for parameter %s, must be 0 or 1\n", idx, pout_name_inv );
      goto fail;
    }

    if ( p_pi->flags & POUT_NOT_INVERTIBLE )
    {
      if ( idx )
      {
        printf( "Warning: Output level can't be inverted for output %i\n", inst_num );
        goto fail;
      }
    }

    if ( idx )
      p_ps->flags |= POUT_INVERTED;
    else
      p_ps->flags &= ~POUT_INVERTED;

    printf( "Output level for output %i%s inverted\n",
            inst_num, idx ? str_empty : str_spc_not );
  }


  // "Only If Sync" flag.
  idx = chk_parm_name( s, pout_name_ois, &cp );

  if ( mbg_rc_is_error( idx ) )  // Parameter error.
  {
    err_info = pout_name_ois;
    goto fail;
  }

  if ( cp )       // Parameter found.
  {
    idx = atoi( cp );

    if ( idx < 0 || idx > 1 )
    {
      printf( "Invalid flag value %i for parameter %s, must be 0 or 1\n", idx, pout_name_ois );
      goto fail;
    }

    if ( !( p_pi->flags & POUT_SUPP_IF_SYNC_ONLY ) )
    {
      if ( idx )
      {
        printf( "Warning: \"Only if sync\" flag not supported for output %i\n", inst_num );
        goto fail;
      }
    }

    if ( idx )
      p_ps->flags |= POUT_IF_SYNC_ONLY;
    else
      p_ps->flags &= ~POUT_IF_SYNC_ONLY;

    printf( "\"Only if sync\" flag%s set for output %i\n",
            idx ? str_empty : str_spc_not, inst_num );
  }


  // "Pulse Shift" parameter.
  idx = chk_parm_name( s, pout_name_shift, &cp );

  if ( mbg_rc_is_error( idx ) )  // Parameter error.
  {
    err_info = pout_name_shift;
    goto fail;
  }

  if ( cp )       // Parameter found.
  {
    long pulse_shift = atol( cp );

    if ( !( p_pi->flags & POUT_SUPP_PULSE_SHIFT ) )
    {
      printf( "Warning: pulse shift not supported for output %i\n", inst_num );
      goto fail;
    }

    if ( !_is_supported( p_ps->mode, POUT_MODES_DATA_PULSE_SHIFT ) )
    {
      printf( "Pulse shift not supported for mode \"%s\"\n",
              _get_pout_mode_name( p_ps->mode ) );
      goto fail;
    }


    if ( ( pulse_shift < DEFAULT_POUT_PULSE_SHIFT_MIN ) ||
         ( pulse_shift > DEFAULT_POUT_PULSE_SHIFT_MAX ) )
    {
      printf( "Pulse shift %li ns out of range (%+li..%+li ns)\n", pulse_shift,
              (long) DEFAULT_POUT_PULSE_SHIFT_MIN, (long) DEFAULT_POUT_PULSE_SHIFT_MAX );
      goto fail;
    }

    if ( p_pi->pulse_shift_res )
    {
      long rem = pulse_shift % p_pi->pulse_shift_res;
      long l = pulse_shift - rem;

      #if 0 && defined( DEBUG )
        printf( "DEBUG: s %li, rem %li, l %li\n", pulse_shift, rem, l );
      #endif

      if ( l != pulse_shift )
      {
        printf( "Warning: pulse shift %+li ns not appropriate for resolution %u ns, truncating to %li ns.\n",
                pulse_shift, p_pi->pulse_shift_res, l );
        pulse_shift = l;
      }
    }

    p_ps->pout_data.pulse_shift = pulse_shift;

    printf( "Pulse shift for programmable output %i changed to %li ns\n",
            inst_num, (long) p_ps->pout_data.pulse_shift );
  }


  for ( i = 0; i < n_pout; i++ )
  {
    POUT_SETTINGS *p_ps = &api[i].pout_info.pout_settings;

    if ( memcmp( p_ps, &prv_api[i].pout_info.pout_settings, sizeof( *p_ps ) ) )
    {
      // Settings for this output have changed.
      rc = mbg_set_gps_pout_settings( dh, p_ps, i );

      if ( mbg_rc_is_error( rc ) )
        return rc;
    }
  }

  return MBG_SUCCESS;

fail:
  printf( "Invalid parameter in argument" );

  if ( err_info )
    printf( " %s", err_info );

  printf( "!\n" );

  return MBG_ERR_CFG;

}  // eval_pout



static /*HDR*/
int show_pout( MBG_DEV_HANDLE dh, const OPT_HANDLER_SPEC *p_opt, const PCPS_DEV *p_devx, const char *cmd_info )
{
  const INDENTS *p_ind = &show_indents;
  RECEIVER_INFO ri = { 0 };
  ALL_POUT_INFO_IDX api = { { 0 } };
  int i;
  int n_pout;
  int rc = check_get_pout_cfg( dh, api, &ri );

  if ( mbg_cond_err_msg( rc, "check_get_pout_cfg" ) )
    return rc;

  n_pout = rc;  // Contains now the number of programmable pulse outputs

  print_indent( p_ind->indent_1 );
  printf( "%s:", cmd_info );

  if ( n_pout )
  {
    for ( i = 0; i < n_pout; i++ )
    {
      const POUT_INFO *pi = &api[i].pout_info;
      const POUT_SETTINGS *ps = &pi->pout_settings;

      // TODO Actually the code below only shows the current mode,
      // and whether the output signal is inverted, or not.
      // Full featured code should also display additional parameters
      // depending the selected mode.

      printf( "\n" );
      print_indent( p_ind->indent_2 );
      printf( "Output %i: ", i );
      printf( "%s", _get_pout_mode_name( ps->mode ) );

      // Print pulse len, if supported by the mode.
      if ( _is_supported( ps->mode, POUT_MODES_MODE_PARAM_AS_PULSE_LEN ) )
      {
        // Pulse len is 10 ms units, so multiply by 10 to get ms.
        printf( ", len %u ms", (unsigned int) ps->mode_param * 10 );

        if ( pi->flags & POUT_FIXED_PULSE_LEN )
          printf( " (fix)" );
      }

      // FIXME TODO check more mode_param usage, times etc.

      // Whether outputs can be inverted doesn't depend on the current mode.
      if ( !( pi->flags & POUT_NOT_INVERTIBLE ) )
        printf( ", %sinverted", ( ps->flags & POUT_INVERTED ) ? str_empty : str_not_spc );



      if ( _is_supported( ps->mode, POUT_MODES_SUPP_IF_SYNC_ONLY ) )
      {
        char ws[80];
        const char *cp = NULL;

        if ( _is_supported( ps->mode, POUT_MODES_TIMEOUT ) &&
             ( ( pi->flags & POUT_SUPP_IF_SYNC_ONLY ) == 0 ) &&
             ( ps->timeout != 0 ) )
        {
          snprintf_safe( ws, sizeof( ws ), "after timeout %i min ", ps->timeout );
          cp = ws;
        }

        if ( pi->flags & POUT_SUPP_IF_SYNC_ONLY )
          printf( ", %sdisabled %sif sync. lost",
                  ( ps->flags & POUT_IF_SYNC_ONLY ) ? str_empty : str_not_spc,
                  cp ? cp : str_empty );
      }




      if ( pi->flags & POUT_SUPP_PULSE_SHIFT )
        if ( _is_supported( ps->mode, POUT_MODES_DATA_PULSE_SHIFT ) )
          printf( ", shift %li ns, res. %li ns", (long) ps->pout_data.pulse_shift, (long) pi->pulse_shift_res );
    }
  }
  else
    printf( str_spc_not_supp );

  printf( "\n" );

  return MBG_SUCCESS;

}  // show_pout



static /*HDR*/
void printf_ef( uint16_t flag, const char *info )
{
  printf( "%s:%u", info, ( flag == EF_OFF ) ? 0 : 1 );

}  // printf_ef



static /*HDR*/
int show_enable_flags( MBG_DEV_HANDLE dh, const PCPS_DEV *p_dev, const char *info )
{
  ENABLE_FLAGS ef;
  int rc;

  rc = mbg_get_gps_enable_flags( dh, &ef );

  if ( mbg_cond_err_msg( rc, "mbg_get_gps_enable_flags" ) )
    return rc;

  printf( "%s enable flags: ", info );
  printf_ef( ef.serial, ef_name_serial );
  printf( "," );
  printf_ef( ef.pulses, ef_name_pulses );

  if ( _pcps_has_synth( p_dev ) )
  {
    printf( "," );
    printf_ef( ef.synth, ef_name_synth );
  }

  printf( "\n" );

  return MBG_SUCCESS;

}  // show_enable_flags



static /*HDR*/
int ef_check_parm( const char *s, EF_INFO *p )
{
  size_t l = strlen( p->name );

  if ( strncmp( s, p->name, l ) != 0 )
    return 0;  // Parameter does not match.

  if ( s[l] != ':' )
    goto fail;  // Parameter syntax error: name not followed by colon.

  l++;

  if ( s[l] != '0' && s[l] != '1' )
    goto fail;  // Parameter syntax error: colon not followed by '0' or '1'.

  *p->flags = ( s[l] == '0' ) ? EF_OFF : p->on_flags;

  l++;

  return _int_from_size_t( l );


fail:
  return MBG_ERR_CFG;

}  // ef_check_parm



static /*HDR*/
int set_enable_flags( MBG_DEV_HANDLE dh, const char *arg, const PCPS_DEV *p_dev )
{
  ENABLE_FLAGS ef;

  EF_INFO ef_parms[N_EF_INFO] =
  {
    { ef_name_serial, &ef.serial, EF_SERIAL_BOTH },
    { ef_name_pulses, &ef.pulses, EF_PULSES_BOTH },
    { ef_name_synth, &ef.synth, EF_SYNTH }
  };

  int rc;

  rc = mbg_get_gps_enable_flags( dh, &ef );

  if ( mbg_cond_err_msg( rc, "mbg_get_gps_enable_flags" ) )
    return rc;

  // Scan input parameters.
  for (;;)
  {
    int i;

    for ( i = 0; i < N_EF_INFO; i++ )
    {
      rc = ef_check_parm( arg, &ef_parms[i] );

      if ( rc == 0 ) // Check next.
        continue;

      if ( rc < 0 )  // Error.
        return rc;

      arg += rc;

      if ( *arg == 0 )  // Done.
        goto save;

      if ( *arg != ',' )
        return MBG_ERR_CFG;  // Invalid parameter, or parameter syntax error.

      arg++;
    }
  }

save:
  rc = mbg_set_gps_enable_flags( dh, &ef );

  if ( mbg_cond_err_msg( rc, "mbg_set_gps_enable_flags" ) )
    return rc;

  return MBG_SUCCESS;

}  // set_enable_flags



static /*HDR*/
int send_gps_cmd( MBG_DEV_HANDLE dh, ushort cmd )
{
  int rc = mbg_set_gps_cmd( dh, &cmd );

  if ( mbg_cond_err_msg( rc, "mbg_set_gps_cmd" ) )
    return rc;

  printf( "NOTE: the command code %u has been sent to the device.\n", cmd );

  return MBG_SUCCESS;

}  // send_gps_cmd



static /*HDR*/
int show_ant_cable_len( MBG_DEV_HANDLE dh, const char *info )
{
  ANT_CABLE_LEN len;
  int rc = mbg_get_gps_ant_cable_len( dh, &len );

  if ( mbg_cond_err_msg( rc, "mbg_get_gps_ant_cable_len" ) )
    return rc;

  printf( "%s antenna cable length: %u meter(s)", info, len );

  return MBG_SUCCESS;

}  // show_ant_cable_len



static /*HDR*/
int set_ant_cable_len( MBG_DEV_HANDLE dh, const char *s )
{
  ANT_CABLE_LEN len = (ANT_CABLE_LEN) atol( s );  // TODO check range ?
  int rc = mbg_set_gps_ant_cable_len( dh, &len );

  if ( mbg_cond_err_msg( rc, "mbg_set_gps_ant_cable_len" ) )
    return rc;

  return MBG_SUCCESS;

}  // set_ant_cable_len



static /*HDR*/
int set_event_time( MBG_DEV_HANDLE dh, const char *s )
{
  char ws[80];
  time_t event_time;
  PCPS_TIME_STAMP event_ts;
  int rc;

  // Set event at current system time + number of seconds.
  event_time = time( NULL ) + strtol( s, NULL, 10 );
  event_ts.sec = (uint32_t) event_time;  // POSIX UTC seconds, TODO check range / conversion.
  event_ts.frac = 0;                     // Fraction of second, 0xFFFFFFFF == 0.99.. sec.

  rc = mbg_set_event_time( dh, &event_ts );

  if ( mbg_cond_err_msg( rc, "mbg_set_event_time" ) )
    return rc;

  mbg_snprint_hr_tstamp( ws, sizeof( ws ), &event_ts, 0, 0 );  // Raw timestamp?
  printf( "Event time set to UTC %s\n", ws );

  return MBG_SUCCESS;

}  // set_event_time



static /*HDR*/
int get_n_time_scale( MBG_DEV_HANDLE dh, MBG_TIME_SCALE_INFO *p_tsci )
{
  MBG_TIME_SCALE_INFO tsci = { { 0 } };
  int rc;

  rc = mbg_chk_dev_has_time_scale( dh );

  if ( mbg_rc_is_error( rc ) )
  {
    if ( rc == MBG_ERR_NOT_SUPP_BY_DEV )
      printf( "This device does not support a configurable time scale.\n" );
    else
      mbg_cond_err_msg( rc, "mbg_chk_dev_has_time_scale" );

    goto done;
  }

  rc = mbg_get_time_scale_info( dh, &tsci );

  if ( rc != MBG_SUCCESS )
    goto done;

  if ( p_tsci )
    *p_tsci = tsci;

done:
  return tsci.max_settings.scale;

}  // get_n_time_scale



static /*HDR*/
int show_time_scale( MBG_DEV_HANDLE dh, const PCPS_DEV *p_dev, const char *info )
{
  MBG_TIME_SCALE_INFO tsci = { { 0 } };
  int rc;

  rc = mbg_get_time_scale_info( dh, &tsci );

  if ( mbg_cond_err_msg( rc, "mbg_get_time_scale_info" ) )
    return rc;

  printf( "%s time scale index: %u (%s)", info, tsci.settings.scale,
          _get_time_scale_name( tsci.settings.scale ) );

  printf( "\n" );

  return MBG_SUCCESS;

}  // show_time_scale



static /*HDR*/
int set_time_scale( MBG_DEV_HANDLE dh, const char *arg, const PCPS_DEV *p_dev )
{
  MBG_TIME_SCALE_INFO tsci = { { 0 } };
  int rc;

  rc = mbg_get_time_scale_info( dh, &tsci );

  if ( mbg_cond_err_msg( rc, "mbg_get_time_scale_info" ) )
    return rc;


  tsci.settings.scale = atoi( arg );

  if ( tsci.settings.scale >= tsci.max_settings.scale )
  {
    printf( "*** Error: new time scale index (%u) out of range (0..%u)\n",
            tsci.settings.scale, tsci.max_settings.scale - 1 );
    return MBG_ERR_CFG;
  }

  if ( !( tsci.supp_scales & ( 1UL << tsci.settings.scale ) ) )
  {
    printf( "*** Warning: new time scale index (%u) not supported by device\n",
            tsci.settings.scale );
    return MBG_ERR_CFG;
  }

  rc = mbg_set_time_scale_settings( dh, &tsci.settings );

  if ( mbg_cond_err_msg( rc, "mbg_set_time_scale_settings" ) )
    return rc;

  return MBG_SUCCESS;

}  // set_time_scale



static /*HDR*/
void usage( MBG_DEV_HANDLE dh, PCPS_DEV *p_dev, RECEIVER_INFO *p_ri,
            RECEIVER_PORT_CFG *p_rpcfg )
{
  int i;
  int n_time_scale;

  if ( p_dev )
    check_get_receiver_port_cfg( dh, p_rpcfg, p_dev, p_ri );

  printf( "Usage:  %s cmd [dev]\n"
          "\n"
          "where cmd can be one of the following:\n"
          "  BOOT             Set GPS receiver to warm boot mode, sat info is kept.\n"
          "  COLDBOOT         Set GPS receiver to cold boot mode, all sat info is cleared.\n"
          "  GPSPOS=x.x,y.y,z Set GPS receiver position to (lat,lon,alt).\n",
          pname
        );


  printf( "  DATE=yyyy-mm-dd  Set on-board date to year, month, day-of-month.\n"
          "  TIME=hh:mm:ss.hh Set on-board time to hours, mins, secs, hundredths.\n"
        );


  printf( "  TIMESCALE        Show time scale of the device, if supported.\n"
          "  TIMESCALE=<n>    Set time scale of the device to scale with index <n>.\n"
        );

  n_time_scale = p_dev ? get_n_time_scale( dh, NULL ) : N_MBG_TIME_SCALE;

  if ( n_time_scale )
  {
    printf( "                   Known time scales:\n" );
    for ( i = 0; i < n_time_scale; i++ )
    {
      printf( "                     %u: %s", i, _get_time_scale_name( i ) );

      if ( i == 0 )
        printf( " (default)" );

      printf( "\n" );
    }
  }
  else
    printf( "                   (Configurable time scales not supported by this device)\n" );


  printf( "  TZOFFS           Show time zone offset of the device, if supported.\n"
          "  TZOFFS=<n>       Set basic time zone of the device to UTC with additional offset, in seconds.\n"
        );

  printf( "  TZ=UTC           Set time zone code to %s.\n"
          "  TZ=CET           Set time zone code to %s.\n"
          "  TZ=EET           Set time zone code to %s.\n",
          tz_info_utc,
          tz_info_cet_cest,
          tz_info_eet_eest
        );


  printf( "  COMPARM          Show COM port parameters of the device.\n"
          "  COM<n>=<bd>,<f>[,<t>[,<m>]]  Set parameters of onboard port COM<n>"
        );

  printf( ", where\n"
          "                     <bd> is one of:" );
  for ( i = 0; i < N_MBG_BAUD_RATES; i++ )
    printf( " %s", mbg_baud_rate_strs[i] );

  printf( "\n"
          "                     <f>  is one of:" );
  for ( i = 0; i < N_MBG_FRAMINGS; i++ )
    printf( " %s", mbg_framing_strs[i] );

  printf( "\n                     <t>  is an optional time string format index" );

  if ( p_dev )
  {
    printf( ":" );

    for ( i = 0; i < p_ri->n_str_type; i ++ )
    {
      const STR_TYPE_INFO *p_sti = &p_rpcfg->stii[i].str_type_info;

      printf( "\n                         %u: %s", i, p_sti->long_name );
    }
  }

  printf( "\n                     <m>  is an optional time string mode index" );

  if ( p_dev )
  {
    printf( ":" );

    for ( i = 0; i < N_STR_MODE; i ++ )
      printf( "\n                         %u: %s", i, mode_names[i] );

    printf( "\n"
            "                    Please note that not every baud rate, framing, string format and mode\n"
            "                    must necessarily be supported by every individual serial port.\n" );
  }

  printf( "\n" );

  help_pout_arg( dh, p_dev, &ohs_pout, 0 );

  printf( "\n" );

  printf( "  EF                             Show enable flags.\n"
          "  EF=SERIAL:0,PULSES:1,SYNTH:0   Modify enable flags.\n"
          "\n"
          "                      SERIAL Controls the serial port output.\n"
          "                      PULSES Controls pulse outputs and IRIG timecode output, if available.\n"
          "                      SYNTH  Controls a programmable synthesizer output, if available.\n"
          "\n"
          "                      0 or 1 Controls when the corresponding output signals are enabled:\n"
          "                             0: only after the device has synchronized to its incoming signal,\n"
          "                             1: immediately after power-up.\n"
          "\n"
          "                      Please note that not every device supports enable flags.\n"
          "\n"
        );

  printf( "  LAN                                        Show LAN interface settings of the device.\n"
          "  LAN=DHCP                                   Set LAN interface to be configured via DHCP.\n"
          "  LAN=IP:<ip>[,NM:<nm>][,BA:<ba>][,GW:<gw>]  Set LAN interface to given static settings.\n"
          "\n"
          "  where each of <ip>,<nm>,<ba>,<gw> is an IPv4 address of the form aaa.bbb.ccc.ddd, e.g.:\n"
          "    IP:192.168.1.115  Specifies the IP address.\n"
          "    NM:255.255.255.0  Specifies the net mask.\n"
          "    BA:192.168.1.255  Specifies the broadcast address.\n"
          "    GW:192.168.1.1    Specifies the default gateway.\n"
          "\n"
          "  If no broadcast address is specified, the default broadcast address\n"
          "  is computed from the IP address and the network mask.\n"
          "\n"
          "  Please note that not every device provides a LAN interface.\n"
          "  Also, the IP values above are examples only. The real values to be used\n"
          "  depend on the settings of the network to which the device is attached.\n"
          "\n"
        );

  printf( "  PTP                                        Show PTP settings of the device.\n"
          "  PTP=NP:<np>[,DM:<dm>][,DO:<do>][,HW:<hw>]  Set general PTP protocol parameters.\n"
          "\n"
          "  where, e.g. :\n"
          "    NP:IP4   Specifies UDP/IPv4   (Layer 3) as network protocol.\n"
          "    NP:ETH   Specifies IEEE 802.3 (Layer 2) as network protocol.\n"
          "    DM:E2E   Specifies end-to-end delay mechanism.\n"
          "    DM:P2P   Specifies peer-to-peer delay mechanism.\n"
          "    DO:0     Specifies PTP domain number [0..255].\n"
          "    HW:1     Specifies if the \"v1 hardware compatibility flag\" shall be set ('1') or disabled ('0')\n"
          "             (this is usually not required).\n"
          "\n"
        );

  printf( "  If the PTP device supports unicast slave mode, the following parameters\n"
          "  can be specified to configure a unicast master to be queried:\n"
          "  PTP=ROLE:<rl>[,GMIP:<ip>][,GMID:<id>][,PID:<po>][,SMI:<sr>][,AMI:<ar>][,DRI:<dr>][,DUR:<du>]  Set PTP unicast parameters.\n"
          "\n"
          "  where, e.g.:\n"
          "    ROLE:MCS                      Specifies \"Multicast Slave\" PTP role.\n"
          "    ROLE:UCS                      Specifies \"Unicast Slave\" PTP role.\n"
          "    GMIP:192.168.1.115            Specifies the IP address of the grandmaster.\n"
          "    GMID:FF:FF:FF:FF:FF:FF:FF:FF  Specifies the Clock ID of the grandmaster, or '*' as wildcard for all 'FF'.\n"
          "    PID:1                         Specifies the target Port ID of the grandmaster port to be used, or '*' for wildcard.\n"
          "    SMI:0                         Specifies the Sync Message Interval requested from the grandmaster in 2^x seconds [-6..6].\n"
          "    AMI:1                         Specifies the Announce Message Interval requested from the grandmaster in 2^x seconds [-6..6].\n"
          "    DRI:1                         Specifies the Delay Request Interval requested from the grandmaster in 2^x seconds [-6..6].\n"
          "    DUR:300                       Specifies the duration in seconds how long the master shall send messages to the slave until a timeout or renewal occurs.\n"
          "\n"
       );

  printf( "  ANT_CABLE_LEN         Show the configured antenna cable length.\n"
          "  ANT_CABLE_LEN=<len>   Set the antenna cable length to be compensated to <len>, in meters.\n"
          "\n"
          "  Please note that this parameter can only be used with devices that support compensation\n"
          "  of the signal propagation delay of the antenna cable, e.g. with GPS/GNSS receivers.\n"
          "\n"
        );

  if ( p_dev )
  {
    if ( _pcps_has_event_time( p_dev ) )
      printf( "  EVENT=<n>         Set event time to system time + <n> seconds.\n" );
  }

  mbg_print_usage_syn1588_support();

}  // usage



static /*HDR*/
const char *str_parm_p( const char *s, const char *keyword )
{
  char *match = strstr( s, keyword );

  if ( match && ( match == s ) )
    return &s[strlen( keyword )];
  else
    return NULL;

}  // str_parm_p



static /*HDR*/
int check_cmd_line( int argc, char *argv[], MBG_DEV_HANDLE dh, const PCPS_DEV *p_dev,
                    RECEIVER_INFO *p_ri, RECEIVER_PORT_CFG *p_rpcfg )
{
  const char *sdate = NULL;
  const char *stime = NULL;
  const char *cp;
  int i;
  int rc = MBG_SUCCESS;
  int error_occurred = 0;

  must_print_usage = false;

  for ( i = 1; i < argc; i++ )
  {
    if ( mbg_rc_is_error( rc ) )
      error_occurred = 1;

    if ( rc == RC_USAGE )
      must_print_usage = true;

    rc = MBG_SUCCESS;

    if ( ( strcmp( argv[i], "-?" ) == 0  ) ||
         ( strcmp( argv[i], "-h" ) == 0  ) ||
         ( strcmp( argv[i], "--help" ) == 0  ) )
    {
      must_print_usage = true;
      continue;
    }

    if ( strcmp( argv[i], "COLDBOOT" ) == 0 )
    {
      if ( p_dev )
      {
        if ( _pcps_is_gps( p_dev ) )
          rc = send_gps_cmd( dh, PC_GPS_CMD_INIT_SYS );
        else
          err_msg( p_dev, no_gps_cmd );
      }
      continue;
    }


    if ( strcmp( argv[i], "BOOT" ) == 0 )
    {
      if ( p_dev )
      {
        if ( _pcps_is_gps( p_dev ) )
          rc = send_gps_cmd( dh, PC_GPS_CMD_BOOT );
        else
          err_msg( p_dev, no_gps_cmd );
      }
      continue;
    }


    cp = str_parm_p( argv[i], "TZ=" );

    if ( cp )
    {
      if ( p_dev )
        rc = set_timezone( dh, cp, p_dev );

      continue;
    }


    cp = str_parm_p( argv[i], "GPSPOS=" );

    if ( cp )
    {
      if ( p_dev )
      {
        if ( _pcps_is_gps( p_dev ) )
          rc = set_gps_pos( dh, cp );
        else
          err_msg( p_dev, no_gps_cmd );
      }
      continue;
    }


    cp = str_parm_p( argv[i], "DATE=" );

    if ( cp )
    {
      sdate = cp;
      continue;
    }


    cp = str_parm_p( argv[i], "TIME=" );

    if ( cp )
    {
      stime = cp;
      continue;
    }


    cp = str_parm_p( argv[i], "COMPARM" );

    if ( cp )
    {
      if ( p_dev )
      {
        int rc = check_get_receiver_port_cfg( dh, p_rpcfg, p_dev, p_ri );

        if ( mbg_rc_is_error( rc ) )
        {
          // ### TODO print another error?
          continue;
        }

        if ( p_ri->n_com_ports )
        {
          if ( *cp != 0 )
          {
            printf( "** Invalid parameter: %s\n", argv[i] );
            must_print_usage = true;
            continue;
          }

          show_serial_settings( dh, p_rpcfg, p_ri );
        }
        else
          printf( "** This device does not provide a configurable COM port.\n" );
      }

      continue;
    }


    cp = str_parm_p( argv[i], "COM" );

    if ( cp )
    {
      if ( p_dev )
      {
        char *p_tail;
        ulong port_num;

        rc = check_get_receiver_port_cfg( dh, p_rpcfg, p_dev, p_ri );

        if ( mbg_rc_is_error( rc ) )
        {
          // ### TODO print another error?
          continue;
        }

        port_num = strtoul( cp, &p_tail, 10 );

        if ( p_tail == cp )  // No COM port number specified.
        {
          printf( "** Invalid COM port specification: %s\n", argv[i] );
          must_print_usage = true;
          continue;
        }

        cp = p_tail;

        if ( port_num >= (ulong) p_ri->n_com_ports )
        {
          printf( "** COM port number %lu exceeds maximum %u\n",
                  port_num, p_ri->n_com_ports );
          must_print_usage = true;
          continue;
        }

        if ( *cp != '=' )
        {
          printf( "** Invalid COM port specification: %s\n", argv[i] );
          must_print_usage = true;
          continue;
        }

        rc = save_serial_settings( dh, (unsigned) port_num, ++cp, p_dev, p_ri );
      }
      continue;
    }


    cp = str_parm_p( argv[i], "POUT" );

    if ( cp )
    {
      if ( p_dev )
      {
        ulong n_pout;
        ulong pout_num;
        char *p_tail;

        check_setup_receiver_info( dh, p_ri );
        n_pout = p_ri->n_prg_out;

        if ( n_pout == 0 )
        {
          printf( "Programmable outputs not supported!\n" );
          continue;
        }

        pout_num = strtoul( cp, &p_tail, 10 );

        if ( p_tail == cp )  // No POUT number specified.
        {
          show_pout( dh, &ohs_pout, p_dev, "Current programmable outputs settings" );
          continue;
        }

        cp = p_tail;

        if ( pout_num >= n_pout )
        {
          printf( "** Programmable output number %lu exceeds maximum %lu\n",
                  pout_num, n_pout );
          must_print_usage = true;
          continue;
        }

        if ( *cp != '=' )
        {
          printf( "** Invalid programmable output specification: %s\n", argv[i] );
          must_print_usage = true;
          continue;
        }

        rc = eval_pout( dh, ++cp, (unsigned) pout_num );
        printf( "\n" );
        show_pout( dh, &ohs_pout, p_dev, "Current programmable outputs settings" );
      }
      continue;
    }


    cp = str_parm_p( argv[i], "EF" );

    if ( cp )
    {
      if ( p_dev )
      {
        char *info = "Current";

        if ( !_pcps_has_gps_data( p_dev ) )
        {
          err_msg( p_dev, no_enable_flags );
          continue;
        }

        if ( *cp == '=' )
        {
          rc = set_enable_flags( dh, ++cp, p_dev );

          if ( mbg_rc_is_error( rc ) )
          {
            printf( "*** Warning: invalid enable flag parameter syntax\n" );
            must_print_usage = true;
            continue;
          }

          info = "New";
        }

        show_enable_flags( dh, p_dev, info );
      }
      continue;
    }


    cp = str_parm_p( argv[i], "TIMESCALE" );

    if ( cp )
    {
      if ( p_dev )
      {
        char *info = "Current";

        if ( !_pcps_has_time_scale( p_dev ) )
        {
          err_msg( p_dev, no_time_scale );
          continue;
        }

        if ( *cp == '=' )
        {
          rc = set_time_scale( dh, ++cp, p_dev );

          if ( mbg_rc_is_error( rc ) )
          {
            must_print_usage = true;
            continue;
          }

          info = "New";
        }

        show_time_scale( dh, p_dev, info );
      }
      continue;
    }


    cp = str_parm_p( argv[i], "TZOFFS" );

    if ( cp  )
    {
      if ( p_dev )
      {
        char *info = "Current";

        if ( !_pcps_has_tzdl( p_dev ) )
        {
          err_msg( p_dev, no_tzdl );
          continue;
        }

        if ( *cp == '=' )
        {
          rc = set_tzdl_offs( dh, ++cp );

          if ( mbg_rc_is_error( rc ) )
          {
            must_print_usage = true;
            continue;
          }

          info = "New";
        }

        show_tzdl_offs( dh, info );
      }
      continue;
    }


    cp = str_parm_p( argv[i], "SYNTH" );

    if ( cp  )
    {
      if ( p_dev )
      {
        char *info = "Current";

        if ( !_pcps_has_synth( p_dev ) )
        {
          err_msg( p_dev, no_synth );
          continue;
        }

        if ( *cp == '=' )
        {
          rc = set_synth( dh, ++cp );

          if ( mbg_rc_is_error( rc ) )
          {
            must_print_usage = true;
            continue;
          }

          info = "New";
        }

        show_synth( dh, info );
      }
      continue;
    }


    cp = str_parm_p( argv[i], "LAN" );

    if ( cp )
    {
      if ( p_dev )
      {
        char *info = "Current";

        if ( !_pcps_has_lan_intf( p_dev ) )
        {
          err_msg( p_dev, no_lan_intf );
          continue;
        }

        if ( *cp == '=' )
        {
          rc = set_lan_intf( dh, ++cp, p_dev );

          if ( mbg_rc_is_error( rc ) )
          {
            must_print_usage = true;
            continue;
          }

          info = "New";
        }

        show_lan_intf( dh, p_dev, info );
      }
      continue;
    }


    cp = str_parm_p( argv[i], "PTP" );

    if ( cp )
    {
      if ( p_dev )
      {
        char *info = "Current";

        if ( !_pcps_has_ptp( p_dev ) )
        {
          err_msg( p_dev, no_ptp );
          continue;
        }

        if ( *cp == '=' )
        {
          rc = set_ptp_cfg( dh, ++cp, p_dev );

          if ( mbg_rc_is_error( rc ) )
            continue;

          info = "New";
        }

        show_ptp_cfg( dh, p_dev, info );
      }
      continue;
    }

    cp = str_parm_p( argv[i], "ANT_CABLE_LEN" );

    if ( cp )
    {
      if ( p_dev )
      {
        char *info = "Current";

        if ( !_pcps_has_cab_len( p_dev ) )
        {
          err_msg( p_dev, no_cab_len );
          continue;
        }

        if ( *cp == '=' )
        {
          rc = set_ant_cable_len( dh, ++cp );

          if ( mbg_rc_is_error( rc ) )
          {
            must_print_usage = true;
            continue;
          }

          info = "New";
        }

        show_ant_cable_len( dh, info );
      }
      continue;
    }


    cp = str_parm_p( argv[i], "EVENT" );

    if ( cp )
    {
      if ( p_dev )
      {
        if ( _pcps_has_event_time( p_dev ) )
        {
          if ( *cp == '=' )
            rc = set_event_time( dh, ++cp );
          else
            rc = MBG_ERR_PARM_FMT;

        if ( mbg_rc_is_error( rc ) )
            printf( "*** Warning: invalid event time parameter\n" );
        }
        else
          err_msg( p_dev, no_event_time );
      }
      continue;
    }

    if ( dev_name == NULL )
      dev_name = argv[i];

#if 0  //##++
    else
    {
      printf( "** Unknown command: %s\n", argv[i] );
      must_print_usage = true;
    }
#endif

  }

  if ( p_dev )
    if ( sdate || stime )
    {
      rc = set_date_time( dh, p_dev, sdate, stime );

      if ( mbg_rc_is_error( rc ) )
        error_occurred = 1;
    }

  if ( error_occurred )
    return MBG_ERR_GENERIC;

  if ( must_print_usage )
    return RC_USAGE;

  return MBG_SUCCESS;

}  // check_cmd_line



int main( int argc, char *argv[] )
{
  RECEIVER_PORT_CFG rpcfg = { { { 0 } } };
  RECEIVER_INFO ri = { 0 };
  PCPS_DEV dev = { { 0 } };
  PCPS_DEV *pdev = NULL;
  MBG_DEV_HANDLE dh = MBG_INVALID_DEV_HANDLE;
  MBG_DEV_FN tmp_dev_fn;
  int rc;

  mbg_print_program_info( pname, MBG_FIRST_COPYRIGHT_YEAR, MBG_LAST_COPYRIGHT_YEAR );

  // If no arguments have been given, just print usage.
  if ( argc < 2 )
    goto show_usage;

  // Check the command line for a device name, but don't
  // pass a device handle, so commands are not evaluated.
  check_cmd_line( argc, argv, dh, NULL, &ri, &rpcfg );

  rc = mbg_open_device_by_param_chk( &dh, dev_name, 0, tmp_dev_fn.s,
                                     sizeof( tmp_dev_fn.s ) );

  if ( mbg_rc_is_error( rc ) )
    goto fail;


  // Get information about the device.
  rc = mbg_get_show_dev_info( dh, NULL, &dev );

  if ( mbg_rc_is_error( rc ) )
    goto fail;


  pdev = &dev;

  rc = check_cmd_line( argc, argv, dh, pdev, &ri, &rpcfg );

  if ( rc < 0 )
    goto fail;

  if ( rc > 0 )
    goto show_usage;

  printf( "\n" );

  mbg_close_device( &dh );

  return MBG_EXIT_CODE_SUCCESS;


show_usage:
  usage( dh, pdev, &ri, &rpcfg );
  return MBG_EXIT_CODE_USAGE;

fail:
  return MBG_EXIT_CODE_FAIL;
}