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

   Includes modifications
   2012, Matthias P. Braendli, matthias.braendli@mpb.li
   */
/*
   This file is part of CRC-DabMux.

   CRC-DabMux is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as
   published by the Free Software Foundation, either version 3 of the
   License, or (at your option) any later version.

   CRC-DabMux is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with CRC-DabMux.  If not, see <http://www.gnu.org/licenses/>.
   */


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

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdio>
#include <cstring>
#include <errno.h>

using namespace std;
#include <vector>
#include <set>
#include <functional>
#include <algorithm>

#ifdef _WIN32
#   include <time.h>
#   include <process.h>
#   include <io.h>
#   include <conio.h>
#   include <winsock2.h> // For types...
typedef u_char uint8_t;
typedef WORD uint16_t;
typedef DWORD32 uint32_t;

#   ifndef __MINGW32__
#       include "xgetopt.h"
#   endif
#   define read _read
#   define snprintf _snprintf 
#   define sleep(a) Sleep((a) * 1000)
#else
#   include <netinet/in.h>
#   include <unistd.h>
#   include <sys/time.h>
#   include <sys/wait.h>
#   include <sys/socket.h>
#   include <sys/ioctl.h>
#   include <sys/times.h>

#   include <linux/if_packet.h>
#   include <linux/netdevice.h>
#endif

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>

#ifdef _WIN32
#   pragma warning ( disable : 4103 )
#   include "Eti.h"
#   pragma warning ( default : 4103 )
#else
#   include "Eti.h"
#endif
#include "dabInputFile.h"
#include "dabInputFifo.h"
#include "dabInputMpegFile.h"
#include "dabInputMpegFifo.h"
#include "dabInputDabplusFile.h"
#include "dabInputDabplusFifo.h"
#include "dabInputPacketFile.h"
#include "dabInputEnhancedPacketFile.h"
#include "dabInputEnhancedFifo.h"
#include "dabInputUdp.h"
#include "dabInputBridgeUdp.h"
#include "dabInputSlip.h"
#include "dabInputTest.h"
#include "dabInputPrbs.h"
#include "dabInputRawFile.h"
#include "dabInputRawFifo.h"
#include "dabInputDmbFile.h"
#include "dabInputDmbUdp.h"


#include "dabOutput.h"
#include "crc.h"
#include "UdpSocket.h"
#include "InetAddress.h"
#include "dabUtils.h"
#include "PcDebug.h"


// DAB Mode
#define DEFAULT_DAB_MODE    2

// Taille de la trame de donnee, sous-canal 3, nb de paquets de 64bits,
// STL3 * 8 = x kbytes par trame ETI

// Data bitrate in kbits/s. Must be 64 kb/s multiple.
#define DEFAULT_DATA_BITRATE    384
#define DEFAULT_PACKET_BITRATE  32

// Etiquettes des sous-canaux et de l'ensemble, 16 characteres incluant les
// espaces
#define DEFAULT_ENSEMBLE_LABEL          "CRC-Dr.Radio"
#define DEFAULT_ENSEMBLE_SHORT_LABEL    0xe000
#define DEFAULT_ENSEMBLE_ID             0xc000
#define DEFAULT_ENSEMBLE_ECC            0xa1

//Numeros des sous-canaux
#define DEFAULT_SERVICE_ID      50
#define DEFAULT_PACKET_ADDRESS  0


struct dabOutput {
    const char* outputProto;
    const char* outputName;
    void* data;
    dabOutputOperations operations;
};


struct dabLabel {
    char text[16];
    uint16_t flag;
};


struct dabService;
struct dabComponent;
struct dabSubchannel;
struct dabEnsemble {
    uint16_t id;
    uint8_t ecc;
    dabLabel label;
    uint8_t mode;
    vector<dabService*> services;
    vector<dabComponent*> components;
    vector<dabSubchannel*> subchannels;
};


struct dabProtectionShort {
    unsigned char tableSwitch;
    unsigned char tableIndex;
};


struct dabProtectionLong {
    unsigned char option;
};


struct dabProtection {
    unsigned char level;
    unsigned char form;
    union {
        dabProtectionShort shortForm;
        dabProtectionLong longForm;
    };
};


struct dabSubchannel {
    const char* inputProto;
    const char* inputName;
    void* data;
    dabInputOperations operations;
    unsigned char id;
    unsigned char type;
    uint16_t startAddress;
    uint16_t bitrate;
    dabProtection protection;
};


class SubchannelId : public std::binary_function <dabSubchannel*, int, bool> {
public:
    bool operator()(const dabSubchannel* subchannel, const int id) const {
        return subchannel->id == id;
    }
};


vector<dabSubchannel*>::iterator getSubchannel(
        vector<dabSubchannel*>& subchannels, int id)
{
    return find_if(
            subchannels.begin(),
            subchannels.end(),
            bind2nd(SubchannelId(), id)
            );
}


struct dabAudioComponent {
};


struct dabDataComponent {
};


struct dabFidcComponent {
};


struct dabPacketComponent {
    uint16_t id;
    uint16_t address;
    uint16_t appType;
    bool datagroup;
};


struct dabComponent {
    dabLabel label;
    uint32_t serviceId;
    uint8_t subchId;
    uint8_t type;
    uint8_t SCIdS;
    union {
        dabAudioComponent audio;
        dabDataComponent data;
        dabFidcComponent fidc;
        dabPacketComponent packet;
    };

    bool isPacketComponent(vector<dabSubchannel*>& subchannels)
    {
        if (subchId > 63) {
            etiLog.printHeader(TcpLog::ERR,
                    "You must define subchannel id in the "
                    "packet component before defining packet ");
            return false;
        }
        if (getSubchannel(subchannels, subchId) == subchannels.end()) {
            etiLog.printHeader(TcpLog::ERR,
                    "Invalid subchannel id in the packet component "
                    "for defining packet ");
            return false;
        }
        if ((*getSubchannel(subchannels, subchId))->type != 3) {
            etiLog.printHeader(TcpLog::ERR,
                    "Invalid component type for defining packet ");
            return false;
        }
        return true;
    }
};


vector<dabComponent*>::iterator getComponent(
        vector<dabComponent*>& components,
        uint32_t serviceId,
        vector<dabComponent*>::iterator current)
{
    if (current == components.end()) {
        current = components.begin();
    } else {
        ++current;
    }

    while (current != components.end()) {
        if ((*current)->serviceId == serviceId) {
            return current;
        }
        ++current;
    }

    return components.end();
}


vector<dabComponent*>::iterator getComponent(
        vector<dabComponent*>& components,
        uint32_t serviceId) {
    return getComponent(components, serviceId, components.end());
}


struct dabService {
    dabLabel label;
    uint32_t id;
    unsigned char pty;
    unsigned char language;
    bool program;

    unsigned char getType(dabEnsemble* ensemble)
    {
        vector<dabSubchannel*>::iterator subchannel;
        vector<dabComponent*>::iterator component =
            getComponent(ensemble->components, id);
        if (component == ensemble->components.end()) {
            return 4;
        }
        subchannel = getSubchannel(ensemble->subchannels, (*component)->subchId);
        if (subchannel == ensemble->subchannels.end()) {
            return 8;
        }

        return (*subchannel)->type;
    }
    unsigned char nbComponent(vector<dabComponent*>& components)
    {
        int nb = 0;
        vector<dabComponent*>::iterator current;

        for (current = components.begin(); current != components.end();
                ++current) {
            if ((*current)->serviceId == id) {
                ++nb;
            }
        }
        return nb;
    }
};


vector<dabService*>::iterator getService(
        dabComponent* component,
        vector<dabService*>& services)
{
    vector<dabService*>::iterator service;

    for (service = services.begin(); service != services.end(); ++service) {
        if ((*service)->id == component->serviceId) {
            break;
        }
    }

    return service;
}


/******************************************************************************
 *****************   Definitions des stuctures des FIGs  **********************
 ******************************************************************************/
struct FIGtype0 {
    uint8_t Length:5;
    uint8_t FIGtypeNumber:3;
    uint8_t Extension:5;
    uint8_t PD:1;
    uint8_t OE:1;
    uint8_t CN:1;
} PACKED;


struct FIGtype0_0 {
    uint8_t Length:5;
    uint8_t FIGtypeNumber:3;
    uint8_t Extension:5;
    uint8_t PD:1;
    uint8_t OE:1;
    uint8_t CN:1;

    uint16_t EId;
    uint8_t CIFcnt_hight:5;
    uint8_t Al:1;
    uint8_t Change:2;
    uint8_t CIFcnt_low:8;
} PACKED;


struct FIGtype0_2 {
    uint8_t Length:5;
    uint8_t FIGtypeNumber:3;
    uint8_t Extension:5;
    uint8_t PD:1;
    uint8_t OE:1;
    uint8_t CN:1;
} PACKED;


struct FIGtype0_2_Service {
    uint16_t SId;
    uint8_t NbServiceComp:4;
    uint8_t CAId:3;
    uint8_t Local_flag:1;
} PACKED;


struct FIGtype0_2_Service_data {
    uint32_t SId;
    uint8_t NbServiceComp:4;
    uint8_t CAId:3;
    uint8_t Local_flag:1;
} PACKED;


struct FIGtype0_2_audio_component {
    uint8_t ASCTy:6;
    uint8_t TMid:2;
    uint8_t CA_flag:1;
    uint8_t PS:1;
    uint8_t SubChId:6;
} PACKED;


struct FIGtype0_2_data_component {
    uint8_t DSCTy:6;
    uint8_t TMid:2;
    uint8_t CA_flag:1;
    uint8_t PS:1;
    uint8_t SubChId:6;
} PACKED;


struct FIGtype0_2_packet_component {
    uint8_t SCId_high:6;
    uint8_t TMid:2;
    uint8_t CA_flag:1;
    uint8_t PS:1;
    uint8_t SCId_low:6;
    void setSCId(uint16_t SCId) {
        SCId_high = SCId >> 6;
        SCId_low = SCId & 0x3f;
    }
} PACKED;


struct FIGtype0_3_header {
    uint8_t Length:5;
    uint8_t FIGtypeNumber:3;
    uint8_t Extension:5;
    uint8_t PD:1;
    uint8_t OE:1;
    uint8_t CN:1;
} PACKED;


/* Warning: When bit SCCA_flag is unset(0), the multiplexer R&S does not send
 * the SCCA field. But, in the Factum ETI analyzer, if this field is not there,
 * it is an error.
 */
struct FIGtype0_3_data {
    uint8_t SCId_high;
    uint8_t SCCA_flag:1;
    uint8_t rfa:3;
    uint8_t SCId_low:4;
    uint8_t DSCTy:6;
    uint8_t rfu:1;
    uint8_t DG_flag:1;
    uint8_t Packet_address_high:2;
    uint8_t SubChId:6;
    uint8_t Packet_address_low;
    uint16_t SCCA;
    void setSCId(uint16_t SCId) {
        SCId_high = SCId >> 4;
        SCId_low = SCId & 0xf;
    }
    void setPacketAddress(uint16_t address) {
        Packet_address_high = address >> 8;
        Packet_address_low = address & 0xff;
    }
} PACKED;


struct FIGtype0_8_short {
    uint8_t SCIdS:4;
    uint8_t rfa_1:3;
    uint8_t ext:1;
    uint8_t Id:6;
    uint8_t MscFic:1;
    uint8_t LS:1;
    uint8_t rfa_2;
} PACKED;


struct FIGtype0_8_long {
    uint8_t SCIdS:4;
    uint8_t rfa_1:3;
    uint8_t ext:1;
    uint8_t SCId_high:4;
    uint8_t rfa:3;
    uint8_t LS:1;
    uint8_t SCId_low;
    uint8_t rfa_2;
    void setSCId(uint16_t id) {
        SCId_high = id >> 8;
        SCId_low = id & 0xff;
    }
    uint16_t getSCid() {
        return (SCId_high << 8) | SCId_low;
    }
} PACKED;


struct FIGtype0_9 {
    uint8_t Length:5;
    uint8_t FIGtypeNumber:3;
    uint8_t Extension:5;
    uint8_t PD:1;
    uint8_t OE:1;
    uint8_t CN:1;

    uint8_t ensembleLto:6;
    uint8_t lto:1;
    uint8_t ext:1;
    uint8_t ensembleEcc;
    uint8_t tableId;
} PACKED;


struct FIGtype0_10 {
    uint8_t Length:5;
    uint8_t FIGtypeNumber:3;
    uint8_t Extension:5;
    uint8_t PD:1;
    uint8_t OE:1;
    uint8_t CN:1;

    uint8_t MJD_high:7;
    uint8_t RFU:1;
    uint8_t MJD_med;
    uint8_t Hours_high:3;
    uint8_t UTC:1;
    uint8_t ConfInd:1;
    uint8_t LSI:1;
    uint8_t MJD_low:2;
    uint8_t Minutes:6;
    uint8_t Hours_low:2;
    void setMJD(uint32_t date) {
        MJD_high = (date >> 10) & 0x7f;
        MJD_med = (date >> 2) & 0xff;
        MJD_low = date & 0x03;
    }
    void setHours(uint16_t hours) {
        Hours_high = (hours >> 2) & 0x07;
        Hours_low = hours & 0x03;
    }
} PACKED;


struct FIGtype0_17_programme {
    uint16_t SId;
    uint8_t NFC:2;
    uint8_t Rfa:2;
    uint8_t CC:1;
    uint8_t L:1;
    uint8_t PS:1;
    uint8_t SD:1;
} PACKED;


struct FIGtype0_1 {
    uint8_t Length:5;
    uint8_t FIGtypeNumber:3;
    uint8_t Extension:5;
    uint8_t PD:1;
    uint8_t OE:1;
    uint8_t CN:1;
} PACKED;


struct FIG_01_SubChannel_ShortF {
    uint8_t StartAdress_high:2;
    uint8_t SubChId:6;
    uint8_t StartAdress_low:8;
    uint8_t TableIndex:6;
    uint8_t TableSwitch:1;
    uint8_t Short_Long_form:1;
} PACKED;


struct FIG_01_SubChannel_LongF {
    uint8_t StartAdress_high:2;
    uint8_t SubChId:6;
    uint8_t StartAdress_low:8;
    uint8_t Sub_ChannelSize_high:2;
    uint8_t ProtectionLevel:2;
    uint8_t Option:3;
    uint8_t Short_Long_form:1;
    uint8_t Sub_ChannelSize_low:8;
} PACKED;


struct FIG0_13_shortAppInfo {
    uint16_t SId;
    uint8_t No:4;
    uint8_t SCIdS:4;
} PACKED;


struct FIG0_13_longAppInfo {
    uint32_t SId;
    uint8_t No:4;
    uint8_t SCIdS:4;
} PACKED;


struct FIG0_13_app {
    uint8_t typeHigh;
    uint8_t length:5;
    uint8_t typeLow:3;
    void setType(uint16_t type) {
        typeHigh = type >> 3;
        typeLow = type & 0x1f;
    }
} PACKED;


struct FIGtype1_0 {
    uint8_t Length:5;
    uint8_t FIGtypeNumber:3;
    uint8_t Extension:3;
    uint8_t OE:1;
    uint8_t Charset:4;

    uint16_t EId;
} PACKED;


struct FIGtype1_1 {
    uint8_t Length:5;
    uint8_t FIGtypeNumber:3;
    uint8_t Extension:3;
    uint8_t OE:1;
    uint8_t Charset:4;

    uint16_t Sld;
} PACKED;


struct FIGtype1_5 {
    uint8_t Length:5;
    uint8_t FIGtypeNumber:3;
    uint8_t Extension:3;
    uint8_t OE:1;
    uint8_t Charset:4;
    uint32_t SId;
} PACKED;


struct FIGtype1_4_programme {
    uint8_t Length:5;
    uint8_t FIGtypeNumber:3;
    uint8_t Extension:3;
    uint8_t OE:1;
    uint8_t Charset:4;
    uint8_t SCIdS:4;
    uint8_t rfa:3;
    uint8_t PD:1;
    uint16_t SId;
} PACKED;


struct FIGtype1_4_data {
    uint8_t Length:5;
    uint8_t FIGtypeNumber:3;
    uint8_t Extension:3;
    uint8_t OE:1;
    uint8_t Charset:4;
    uint8_t SCIdS:4;
    uint8_t rfa:3;
    uint8_t PD:1;
    uint32_t SId;
} PACKED;


#ifdef _WIN32
#   pragma pack(pop)
#endif

static unsigned char Padding_FIB[] = {
    0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};

/******************************************************************************
 *************  Tables pour l'identification des fichiers mp2  ****************
 *****************************************************************************/
const unsigned short Bit_Rate_SpecifiedTable[16] = {
    0, 32, 48, 56, 64, 80, 96, 112,
    128, 160, 192, 224, 256, 320, 384, 0
};


const unsigned short Sub_Channel_SizeTable[64] = {
    16, 21, 24, 29, 35, 24, 29, 35,
    42, 52, 29, 35, 42, 52, 32, 42,
    48, 58, 70, 40, 52, 58, 70, 84,
    48, 58, 70, 84, 104, 58, 70, 84,
    104, 64, 84, 96, 116, 140, 80, 104,
    116, 140, 168, 96, 116, 140, 168, 208,
    116, 140, 168, 208, 232, 128, 168, 192,
    232, 280, 160, 208, 280, 192, 280, 416
};


const unsigned char ProtectionLevelTable[64] = {
    4, 3, 2, 1, 0, 4, 3, 2,
    1, 0, 4, 3, 2, 1, 4, 3,
    2, 1, 0, 4, 3, 2, 1, 0,
    4, 3, 2, 1, 0, 4, 3, 2,
    1, 4, 3, 2, 1, 0, 4, 3,
    2, 1, 0, 4, 3, 2, 1, 0,
    4, 3, 2, 1, 0, 4, 3, 2,
    1, 0, 4, 3, 1, 4, 2, 0
};


const unsigned short BitRateTable[64] = {
    32, 32, 32, 32, 32, 48, 48, 48,
    48, 48, 56, 56, 56, 56, 64, 64,
    64, 64, 64, 80, 80, 80, 80, 80,
    96, 96, 96, 96, 96, 112, 112, 112,
    112, 128, 128, 128, 128, 128, 160, 160,
    160, 160, 160, 192, 192, 192, 192, 192,
    224, 224, 224, 224, 224, 256, 256, 256,
    256, 256, 320, 320, 320, 384, 384, 384
};


unsigned short getSizeByte(dabSubchannel* subchannel)
{
    return subchannel->bitrate * 3;
}


unsigned short getSizeWord(dabSubchannel* subchannel)
{
    return (subchannel->bitrate * 3) >> 2;
}


unsigned short getSizeDWord(dabSubchannel* subchannel)
{
    return (subchannel->bitrate * 3) >> 3;
}


unsigned short getSizeCu(dabSubchannel* subchannel)
{
    if (subchannel->protection.form == 0) {
        return Sub_Channel_SizeTable[subchannel->
            protection.shortForm.tableIndex];
    } else {
        dabProtectionLong* protection =
            &subchannel->protection.longForm;
        switch (protection->option) {
        case 0:
            switch (subchannel->protection.level) {
            case 0:
                return (subchannel->bitrate * 12) >> 3;
                break;
            case 1:
                return subchannel->bitrate;
                break;
            case 2:
                return (subchannel->bitrate * 6) >> 3;
                break;
            case 3:
                return (subchannel->bitrate >> 1);
                break;
            default: // Should not happens
                etiLog.print(TcpLog::ERR, "Bad protection level on "
                        "subchannel\n");
                return 0;
            }
            break;
        case 1:
            switch (subchannel->protection.level) {
            case 0:
                return (subchannel->bitrate * 27) >> 5;
                break;
            case 1:
                return (subchannel->bitrate * 21) >> 5;
                break;
            case 2:
                return (subchannel->bitrate * 18) >> 5;
                break;
            case 3:
                return (subchannel->bitrate * 15) >> 5;
                break;
            default: // Should not happens
                etiLog.print(TcpLog::ERR,
                        "Bad protection level on subchannel\n");
                return 0;
            }
            break;
        default:
            etiLog.print(TcpLog::ERR, "Invalid protection option\n");
            return 0;
        }
    }
    return 0;
}


time_t getDabTime()
{
    static time_t oldTime = 0;
    static int offset = 0;
    if (oldTime == 0) {
        oldTime = time(NULL);
    } else {
        offset+= 24;
        if (offset >= 1000) {
            offset -= 1000;
            ++oldTime;
        }
    }
    return oldTime;
}


void printUsage(char *name, FILE* out = stderr)
{
    fprintf(out, "NAME\n");
    fprintf(out, "  %s - A software DAB multiplexer\n", name);
    fprintf(out, "\nSYNOPSYS\n");
    fprintf(out, "  %s"
            " [ensemble]"
            " [subchannel1 subchannel2 ...]"
            " [service1 component1 [component2 ...] service2 ...]"
            " [output1 ...]"
            " [-h]"
            " [-m mode]"
            " [-n nbFrames]"
            " [-o]"
            " [-s]"
            " [-V]"
            " [-z]"
            "\n",
            name);
    fprintf(out, "\n  Where ensemble ="
            " [-i ensembleId]"
            " [-L label]"
            " [-l sLabel]"
            "\n");
    fprintf(out, "\n  Where subchannel ="
            " -(A | B | D | E | F | M | P | T) inputName"
            " [-b bitrate]"
            " [-i subchannelId]"
            " [-k]"
            " [-p protection]"
            "\n");
    fprintf(out, "\n  Where service ="
            " -S"
            " [-g language]"
            " [-i serviceId]"
            " [-L label]"
            " [-l sLabel]"
            " [-y PTy]"
            "\n");
    fprintf(out, "\n  Where component ="
            " -C"
            " [-a address]"
            " [-d]"
            " [-f figType]"
            " [-i subchannelId]"
            " [-L label]"
            " [-l sLabel]"
            " [-t type]"
            "\n");
    fprintf(out, "\nDESCRIPTION\n");
    fprintf(out,
            "  %s  is  a  software  multiplexer  that generates an ETI stream from\n"
            "  audio and data streams. Because of  its  software  based  architecture,\n"
            "  many  typical DAB services can be generated and multiplexed on a single\n"
            "  PC platform with live or pre-recorded sources.\n"
            "\n"
            "  A DAB multiplex configuration is composed of one ensemble. An  ensemble\n"
            "  is  the entity that receivers tune to and process. An ensemble contains\n"
            "  several services. A service is  the  listener-selectable  output.  Each\n"
            "  service  contains  one mandatory service component which is called pri-\n"
            "  mary component. An audio primary component  define  a  program  service\n"
            "  while  a data primary component define a data service. Service can con-\n"
            "  tain additional components which are called secondary components. Maxi-\n"
            "  mum  total  number  of components is 12 for program services and 11 for\n"
            "  data services. A service component is a link to one subchannel (of Fast\n"
            "  Information  Data  Channel).  A  subchannel  is the physical space used\n"
            "  within the common interleaved frame.\n"
            "\n"
            "   __________________________________________________\n"
            "  |                   CRC-Ensemble                   |  ENSEMBLE\n"
            "  |__________________________________________________|\n"
            "          |                 |                 |\n"
            "          |                 |                 |\n"
            "   _______V______    _______V______    _______V______\n"
            "  | CRC-Service1 |  | CRC-Service2 |  | CRC-Service3 |  SERVICES\n"
            "  |______________|  |______________|  |______________|\n"
            "     |        |        |        | |______         |\n"
            "     |        |        |        |        |        |\n"
            "   __V__    __V__    __V__    __V__    __V__    __V__\n"
            "  | SC1 |  | SC2 |  | SC3 |  | SC4 |  | SC5 |  | SC6 |  SERVICE\n"
            "  |_____|  |_____|  |_____|  |_____|  |_____|  |_____|  COMPONENTS\n"
            "     |        |   _____|        |        |    ____|\n"
            "     |        |  |              |        |   |\n"
            "   __V________V__V______________V________V___V_______   COMMON\n"
            "  | SubCh1 | SubCh9 |  ...  | SubCh3 | SubCh60 | ... |  INTERLEAVED\n"
            "  |________|________|_______|________|_________|_____|  FRAME\n"
            "  Figure 1: An example of a DAB multiplex configuration\n",
        name);

    fprintf(out, "\nGENERAL OPTIONS\n");
    fprintf(out, "  -h                   : get this help\n");
    fprintf(out, "  -m                   : DAB mode (default: 2)\n");
    fprintf(out, "  -n nbFrames          : number of frames to produce\n");
    fprintf(out, "  -o                   : turn on TCP log on port 12222\n");
    fprintf(out, "  -r                   : throttle the output rate to one ETI frame every 24ms\n");
    fprintf(out, "  -V                   : print version information and "
            "exit\n");
    fprintf(out, "  -z                   : write SCCA field for Factum ETI"
            " analyzer\n");
    fprintf(out, "\nINPUT OPTIONS\n");
    fprintf(out, "  -A                   : set audio service\n");
    fprintf(out, "  -B                   : set CRC-Bridge data service\n");
    fprintf(out, "  -D                   : set data service\n");
    fprintf(out, "  -E                   : set enhanced packet service\n");
    fprintf(out, "  -F                   : set DAB+ service\n");
    fprintf(out, "  -M                   : set DMB service\n");
    fprintf(out, "  -P                   : set packet service\n");
    fprintf(out, "  -T                   : set test service\n");
    fprintf(out, "  inputName<n>         : name of file for audio and "
            "packet service and Udp input address for data service "
            "([address]:port)\n");
    fprintf(out, "  -a                   : packet address (default: 0x%x "
            "(%i))\n", DEFAULT_PACKET_ADDRESS, DEFAULT_PACKET_ADDRESS);
    fprintf(out, "  -b bitrate<n>        : bitrate (in kbits/s) of the "
            "subchannel (default: audio 1st frame, data %i, packet %i)\n",
            DEFAULT_DATA_BITRATE, DEFAULT_PACKET_BITRATE);
    fprintf(out, "  -c                   : set the extendend country code ECC "
            "(default: %u (0x%2x)\n", DEFAULT_ENSEMBLE_ECC, DEFAULT_ENSEMBLE_ECC);
    fprintf(out, "  -d                   : turn on datagroups in packet "
            "mode\n");
    fprintf(out, "  -f figType           : user application type in FIG "
            "0/13 for packet mode\n");
    fprintf(out, "  -g language          : Primary service component "
            "language: english=9, french=15\n");
    fprintf(out, "  -i id<n>             : service|subchannel|"
            "serviceComponent id <n> (default: <n>)\n");
    fprintf(out, "  -k                   : set non-blocking file input "
            "(audio and packet only)\n");
    fprintf(out, "  -L label<n>          : label of service <n>"
            " (default: CRC-Audio<n>)\n");
    fprintf(out, "  -l sLabel<n>         : short label flag of service <n>"
            " (default: 0xf040)\n");
    fprintf(out, "  -p protection<n>     : protection level (default: 3)\n");
    fprintf(out, "  -s                   : enable TIST, synchronized on 1PPS at level 2. This also transmits time using the MNSC.\n");
    fprintf(out, "  -t type              : audio/data service component type"
            " (default: 0)\n");
    fprintf(out, "                         audio: foreground=0, "
            "background=1, multi-channel=2\n");
    fprintf(out, "                         data: unspecified=0, TMC=1, "
            "EWS=2, ITTS=3, paging=4, TDC=5, DMB=24, IP=59, MOT=60, "
            "proprietary=61\n");
    fprintf(out, "  -y PTy               : Primary service component program"
            " type international code\n");
    fprintf(out, "\nOUTPUT OPTIONS\n");
    fprintf(out, "  -O output            : name of the output in format "
            "scheme://[address][:port][/name]\n"
            "                         where scheme is (raw|udp|tcp|file|fifo|simul)\n"
           );
}


bool running = true;

void signalHandler(int signum)
{
#ifdef _WIN32
    etiLog.print(TcpLog::DBG, "\npid: %i\n", _getpid());
#else
    etiLog.print(TcpLog::DBG, "\npid: %i, ppid: %i\n", getpid(), getppid());
#endif
    etiLog.print(TcpLog::DBG, "Signal handler called with signal ");
    switch (signum) {
#ifndef _WIN32
    case SIGHUP:
        etiLog.print(TcpLog::DBG, "SIGHUP\n");
        break;
    case SIGQUIT:
        etiLog.print(TcpLog::DBG, "SIGQUIT\n");
        break;
    case SIGPIPE:
        etiLog.print(TcpLog::DBG, "SIGPIPE\n");
        return;
        break;
#endif
    case SIGINT:
        etiLog.print(TcpLog::DBG, "SIGINT\n");
        break;
    case SIGTERM:
        etiLog.print(TcpLog::DBG, "SIGTERM\n");
        etiLog.print(TcpLog::DBG, "Exiting software\n");
        exit(0);
        break;
    default:
        etiLog.print(TcpLog::DBG, "number %i\n", signum);
    }
#ifndef _WIN32
    killpg(0, SIGPIPE);
#endif
    running = false;
}


void printEnsemble(dabEnsemble* ensemble)
{
    char label[17];
    memcpy(label, ensemble->label.text, 16);
    label[16] = 0;

    etiLog.printHeader(TcpLog::INFO, "Ensemble\n");
    etiLog.printHeader(TcpLog::INFO, " id:          0x%lx (%lu)\n",
            ensemble->id, ensemble->id);
    etiLog.printHeader(TcpLog::INFO, " ecc:         0x%x (%u)\n",
            ensemble->ecc, ensemble->ecc);
    etiLog.printHeader(TcpLog::INFO, " label:       %s\n", label);
    etiLog.printHeader(TcpLog::INFO, " short label: ");
    for (int i = 0; i < 32; ++i) {
        if (ensemble->label.flag & 0x8000 >> i) {
            etiLog.printHeader(TcpLog::INFO, "%c", ensemble->label.text[i]);
        }
    }
    etiLog.printHeader(TcpLog::INFO, " (0x%x)\n", ensemble->label.flag);
    etiLog.printHeader(TcpLog::INFO, " mode:        %u\n", ensemble->mode);
}


void printSubchannels(vector<dabSubchannel*>& subchannels)
{
    vector<dabSubchannel*>::iterator subchannel;
    int index = 0;

    for (subchannel = subchannels.begin(); subchannel != subchannels.end();
            ++subchannel) {
        dabProtection* protection = &(*subchannel)->protection;
        etiLog.printHeader(TcpLog::INFO, "Subchannel   %i\n", index);
        etiLog.printHeader(TcpLog::INFO, " input\n");
        etiLog.printHeader(TcpLog::INFO, "   protocol: %s\n",
                (*subchannel)->inputProto);
        etiLog.printHeader(TcpLog::INFO, "   name:     %s\n",
                (*subchannel)->inputName);
        etiLog.printHeader(TcpLog::INFO, " type:       ");
        switch ((*subchannel)->type) {
        case 0:
            etiLog.printHeader(TcpLog::INFO, "audio\n");
            break;
        case 1:
            etiLog.printHeader(TcpLog::INFO, "data\n");
            break;
        case 2:
            etiLog.printHeader(TcpLog::INFO, "fidc\n");
            break;
        case 3:
            etiLog.printHeader(TcpLog::INFO, "packet\n");
            break;
        default:
            etiLog.printHeader(TcpLog::INFO, "Unknown data type "
                    "(service->type)\n");
            break;
        }
        etiLog.printHeader(TcpLog::INFO, " id:         %i\n",
                (*subchannel)->id);
        etiLog.printHeader(TcpLog::INFO, " bitrate:    %i\n",
                (*subchannel)->bitrate);
        etiLog.printHeader(TcpLog::INFO, " protection: ");
        if (protection->form == 0) {
            etiLog.printHeader(TcpLog::INFO, "UEP %i\n", protection->level + 1);
        } else {
            etiLog.printHeader(TcpLog::INFO, "EEP %i-%c\n",
                    protection->level + 1,
                    protection->longForm.option == 0 ? 'A' : 'B');
        }
        if (protection->form == 0) {
            etiLog.printHeader(TcpLog::INFO,
                    "  form:      short\n  switch:    %i\n  index:     %i\n",
                    protection->shortForm.tableSwitch,
                    protection->shortForm.tableIndex);
        } else {
            etiLog.printHeader(TcpLog::INFO,
                    "  form:      long\n  option:    %i\n  level:     %i\n",
                    protection->longForm.option,
                    (*subchannel)->protection.level);
        }
        etiLog.printHeader(TcpLog::INFO, " SAD:        %i\n",
                (*subchannel)->startAddress);
        etiLog.printHeader(TcpLog::INFO, " size (CU):  %i\n",
                getSizeCu(*subchannel));
        ++index;
    }
}


void printComponent(dabComponent* component)
{
    char label[17];
    memcpy(label, component->label.text, 16);
    label[16] = 0;
    if (label[0] == 0) {
        sprintf(label, "<none>");
    }

    etiLog.printHeader(TcpLog::INFO, " service id:             %i\n",
            component->serviceId);
    etiLog.printHeader(TcpLog::INFO, " subchannel id:          %i\n",
            component->subchId);
    etiLog.printHeader(TcpLog::INFO, " label:                  %s\n",
            label);
    etiLog.printHeader(TcpLog::INFO, " short label:            ");
    for (int i = 0; i < 32; ++i) {
        if (component->label.flag & 0x8000 >> i) {
            etiLog.printHeader(TcpLog::INFO, "%c", component->label.text[i]);
        }
    }
    etiLog.printHeader(TcpLog::INFO, " (0x%x)\n", component->label.flag);
    etiLog.printHeader(TcpLog::INFO, " service component type: 0x%x (%u)\n",
            component->type, component->type);
    etiLog.printHeader(TcpLog::INFO, " (packet) id:            %u\n",
            component->packet.id);
    etiLog.printHeader(TcpLog::INFO, " (packet) address:       %u\n",
            component->packet.address);
    etiLog.printHeader(TcpLog::INFO, " (packet) app type:      %u\n",
            component->packet.appType);
    etiLog.printHeader(TcpLog::INFO, " (packet) datagroup:     %u\n",
            component->packet.datagroup);
}


void printComponents(vector<dabComponent*>& components)
{
    vector<dabComponent*>::const_iterator current;
    unsigned int index = 0;

    for (current = components.begin(); current != components.end(); ++current) {
        etiLog.printHeader(TcpLog::INFO, "Component       %i\n", index);
        printComponent(*current);
        ++index;
    }
}


void printServices(vector<dabService*>& services)
{
    vector<dabService*>::const_iterator current;
    int index = 0;

    for (current = services.begin(); current != services.end(); ++current) {
        char label[17];
        memcpy(label, (*current)->label.text, 16);
        label[16] = 0;

        etiLog.printHeader(TcpLog::INFO, "Service       %i\n", index);
        etiLog.printHeader(TcpLog::INFO, " label:       %s\n", label);
        etiLog.printHeader(TcpLog::INFO, " short label: ");
        for (int i = 0; i < 32; ++i) {
            if ((*current)->label.flag & 0x8000 >> i) {
                etiLog.printHeader(TcpLog::INFO, "%c", (*current)->label.text[i]);
            }
        }
        etiLog.printHeader(TcpLog::INFO, " (0x%x)\n", (*current)->label.flag);
        etiLog.printHeader(TcpLog::INFO, " id:          0x%lx (%lu)\n",
                (*current)->id, (*current)->id);
        etiLog.printHeader(TcpLog::INFO, " pty:         0x%x (%u)\n",
                (*current)->pty, (*current)->pty);
        etiLog.printHeader(TcpLog::INFO, " language:    0x%x (%u)\n",
                (*current)->language, (*current)->language);
        ++index;
    }
}


void printOutputs(vector<dabOutput*>& outputs)
{
    vector<dabOutput*>::const_iterator output;
    int index = 0;

    for (output = outputs.begin(); output != outputs.end(); ++output) {
        etiLog.printHeader(TcpLog::INFO, "Output      %i\n", index);
        etiLog.printHeader(TcpLog::INFO, "  protocol: %s\n",
                (*output)->outputProto);
        etiLog.printHeader(TcpLog::INFO, "  name:     %s\n",
                (*output)->outputName);
        ++index;
    }
}


int main(int argc, char *argv[])
{
    etiLog.printHeader(TcpLog::INFO,
            "Welcome to %s %s, compiled at %s, %s\n\n",
            PACKAGE_NAME, PACKAGE_VERSION, __DATE__, __TIME__);
    etiLog.printHeader(TcpLog::INFO,
            "Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011\n"
            "Her Majesty the Queen in Right of Canada,\n"
            "(Communications Research Centre Canada) All rights reserved.\n\n");
    etiLog.printHeader(TcpLog::INFO, "Input URLs supported:");
#if defined(HAVE_INPUT_PRBS)
    etiLog.printHeader(TcpLog::INFO, " prbs");
#endif
#if defined(HAVE_INPUT_TEST)
    etiLog.printHeader(TcpLog::INFO, " test");
#endif
#if defined(HAVE_INPUT_SLIP)
    etiLog.printHeader(TcpLog::INFO, " slip");
#endif
#if defined(HAVE_INPUT_UDP)
    etiLog.printHeader(TcpLog::INFO, " udp");
#endif
#if defined(HAVE_INPUT_FIFO)
    etiLog.printHeader(TcpLog::INFO, " fifo");
#endif
#if defined(HAVE_INPUT_FILE)
    etiLog.printHeader(TcpLog::INFO, " file");
#endif
    etiLog.printHeader(TcpLog::INFO, "\n");

    etiLog.printHeader(TcpLog::INFO, "Inputs format supported:");
#if defined(HAVE_FORMAT_RAW)
    etiLog.printHeader(TcpLog::INFO, " raw");
#endif
#if defined(HAVE_FORMAT_BRIDGE)
    etiLog.printHeader(TcpLog::INFO, " bridge");
#endif
#if defined(HAVE_FORMAT_MPEG)
    etiLog.printHeader(TcpLog::INFO, " mpeg");
#endif
#if defined(HAVE_FORMAT_PACKET)
    etiLog.printHeader(TcpLog::INFO, " packet");
#endif
#if defined(HAVE_FORMAT_DMB)
    etiLog.printHeader(TcpLog::INFO, " dmb");
#endif
#if defined(HAVE_FORMAT_EPM)
    etiLog.printHeader(TcpLog::INFO, " epm");
#endif
    etiLog.printHeader(TcpLog::INFO, "\n");

    etiLog.printHeader(TcpLog::INFO, "Output URLs supported:");
#if defined(HAVE_OUTPUT_FILE)
    etiLog.printHeader(TcpLog::INFO, " file");
#endif
#if defined(HAVE_OUTPUT_FIFO)
    etiLog.printHeader(TcpLog::INFO, " fifo");
#endif
#if defined(HAVE_OUTPUT_UDP)
    etiLog.printHeader(TcpLog::INFO, " udp");
#endif
#if defined(HAVE_OUTPUT_TCP)
    etiLog.printHeader(TcpLog::INFO, " tcp");
#endif
#if defined(HAVE_OUTPUT_RAW)
    etiLog.printHeader(TcpLog::INFO, " raw");
#endif
#if defined(HAVE_OUTPUT_SIMUL)
    etiLog.printHeader(TcpLog::INFO, " simul");
#endif
    etiLog.printHeader(TcpLog::INFO, "\n\n");

    /*    for (int signum = 1; signum < 16; ++signum) {
          signal(signum, signalHandler);
          }*/
#ifndef _WIN32
    signal(SIGHUP, signalHandler);
    signal(SIGQUIT, signalHandler);
#endif
    signal(SIGINT, signalHandler);
    signal(SIGTERM, signalHandler);
    //signal(SIGPIPE, signalHandler);

#ifdef _WIN32
    if (SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST) == 0) {
        etiLog.printHeader(TcpLog::WARNING, "Can't increase priority: %s\n",
                strerror(errno));
    }
#else
    if (setpriority(PRIO_PROCESS, 0, -20) == -1) {
        etiLog.printHeader(TcpLog::WARNING, "Can't increase priority: %s\n",
                strerror(errno));
    }
#endif
    /*sched_param scheduler;
      scheduler.sched_priority = 99;        // sched_get_priority_max(SCHED_RR)
      if (sched_setscheduler(0, SCHED_RR, &scheduler) == -1) {
      etiLog.print(TcpLog::WARNING, "Can't increased priority: %s\n",
      strerror(errno));
      }*/

    uint8_t watermarkData[128];
    size_t watermarkSize = 0;
    size_t watermarkPos = 0;
    {
        uint8_t buffer[sizeof(watermarkData) / 2];
        snprintf((char*)buffer, sizeof(buffer),
                "%s %s, compiled at %s, %s",
                PACKAGE_NAME, PACKAGE_VERSION, __DATE__, __TIME__);
        memset(watermarkData, 0, sizeof(watermarkData));
        watermarkData[0] = 0x55; // Sync
        watermarkData[1] = 0x55;
        watermarkSize = 16;
        for (unsigned i = 0; i < strlen((char*)buffer); ++i) {
            for (int j = 0; j < 8; ++j) {
                uint8_t bit = (buffer[watermarkPos >> 3] >> (7 - (watermarkPos & 0x07))) & 1;
                watermarkData[watermarkSize >> 3] |= bit << (7 - (watermarkSize & 0x07));
                ++watermarkSize;
                bit = 1;
                watermarkData[watermarkSize >> 3] |= bit << (7 - (watermarkSize & 0x07));
                ++watermarkSize;
                ++watermarkPos;
            }
        }
    }
    watermarkPos = 0;


    dabEnsemble* ensemble = new dabEnsemble;
    strncpy(ensemble->label.text, DEFAULT_ENSEMBLE_LABEL, 16);
    ensemble->mode = DEFAULT_DAB_MODE;
    ensemble->label.flag = DEFAULT_ENSEMBLE_SHORT_LABEL;
    ensemble->id = DEFAULT_ENSEMBLE_ID;
    ensemble->ecc = DEFAULT_ENSEMBLE_ECC;

    vector<dabOutput*> outputs;
    vector<dabService*>::iterator service = ensemble->services.end();
    vector<dabService*>::iterator serviceProgramInd;
    vector<dabService*>::iterator serviceDataInd;
    vector<dabService*>::iterator servicePty;
    vector<dabComponent*>::iterator component = ensemble->components.end();
    vector<dabComponent*>::iterator componentIndicatorProgram;
    vector<dabComponent*>::iterator componentIndicatorData;
    vector<dabSubchannel*>::iterator subchannel = ensemble->subchannels.end();
    vector<dabSubchannel*>::iterator subchannelIndicator;
    vector<dabOutput*>::iterator output;
    dabProtection* protection = NULL;

    unsigned int currentFrame;
    int returnCode = 0;
    int result;
    int cur;
    unsigned char etiFrame[6144];
    unsigned short index = 0;
    //FIC Length, DAB Mode I, II, IV -> FICL = 24, DAB Mode III -> FICL = 32
    unsigned FICL  = (ensemble->mode == 3 ? 32 : 24);

    unsigned long sync = 0x49C5F8;
    unsigned short FLtmp = 0;
    unsigned short nbBytesCRC = 0;
    unsigned short CRCtmp = 0xFFFF;
    unsigned short MSTsize = 0;

    unsigned int insertFIG = 0;
    unsigned int alterneFIB = 0;

    bool factumAnalyzer = false;
    unsigned long limit = 0;
    time_t date;
    bool enableTist = false;
    unsigned timestamp = 0;

    unsigned long time_seconds = 0;

    struct timeval mnsc_time;

    /* TODO: 
     * In a SFN, when reconfiguring the ensemble, the multiplexer
     * has to be restarted (crc-dabmux doesn't support reconfiguration).
     * Ideally, we must be able to restart transmission s.t. the receiver
     * synchronisation is preserved.
     */
    gettimeofday(&mnsc_time, NULL);

    bool MNSC_increment_time = false;

    char* progName = strrchr(argv[0], '/');
    if (progName == NULL) {
        progName = argv[0];
    } else {
        ++progName;
    }


    while (1) {
        int c = getopt(argc, argv,
                "A:B:CD:E:F:L:M:O:P:STVa:b:c:de:f:g:hi:kl:m:n:op:rst:y:z");
        if (c == -1) {
            break;
        }
        switch (c) {
        case 'O':
            outputs.push_back(new dabOutput);
            output = outputs.end() - 1;

            memset(*output, 0, sizeof(dabOutput));
            (*output)->outputProto = NULL;
            (*output)->outputName = NULL;
            (*output)->data = NULL;
            (*output)->operations = dabOutputDefaultOperations;

            char* proto;

            proto = strstr(optarg, "://");
            if (proto == NULL) {
                etiLog.printHeader(TcpLog::ERR,
                        "No protocol defined for output\n");
                returnCode = -1;
                goto EXIT;
            } else {
                (*output)->outputProto = optarg;
                (*output)->outputName = proto + 3;
                *proto = 0;
            }
            subchannel = ensemble->subchannels.end();
            protection = NULL;
            component = ensemble->components.end();
            service = ensemble->services.end();
            break;
        case 'S':
            ensemble->services.push_back(new dabService);

            subchannel = ensemble->subchannels.end();
            protection = NULL;
            component = ensemble->components.end();
            service = ensemble->services.end() - 1;
            output = outputs.end();

            memset((*service)->label.text, 0, 16);
            sprintf((*service)->label.text, "CRC-Service%i",
                    (int)ensemble->services.size());
            (*service)->label.flag = 0xe01f;
            (*service)->id = DEFAULT_SERVICE_ID + ensemble->services.size();
            (*service)->pty = 0;
            (*service)->language = 0;
            currentFrame = 0;    // Will be used temporaly for SCIdS

            break;
        case 'C':
            if (service == ensemble->services.end()) {
                etiLog.printHeader(TcpLog::ERR, "You must define a service"
                        " before using option -%c\n", c);
                printUsage(progName);
                returnCode = -1;
                goto EXIT;
            }

            ensemble->components.push_back(new dabComponent);

            component = ensemble->components.end() - 1;
            subchannel = ensemble->subchannels.end();
            protection = NULL;
            output = outputs.end();

            memset(*component, 0, sizeof(dabComponent));
            memset((*component)->label.text, 0, 16);
            (*component)->label.flag = 0xffff;
            (*component)->serviceId = (*service)->id;
            (*component)->subchId = (*(ensemble->subchannels.end() - 1))->id;
            (*component)->SCIdS = currentFrame++;
            break;
        case 'A':
        case 'B':
        case 'D':
        case 'E':
        case 'F':
        case 'M':
        case 'P':
        case 'T':
            if (optarg == NULL && c != 'T') {
                etiLog.printHeader(TcpLog::ERR,
                        "Missing parameter for option -%c\n", c);
                printUsage(progName);
                returnCode = -1;
                goto EXIT;
            }

            ensemble->subchannels.push_back(new dabSubchannel);

            subchannel = ensemble->subchannels.end() - 1;
            protection = &(*subchannel)->protection;
            component = ensemble->components.end();
            service = ensemble->services.end();
            output = outputs.end();

            if (c != 'T') {
                (*subchannel)->inputName = optarg;
            } else {
                (*subchannel)->inputName = NULL;
            }
            if (0) {
#if defined(HAVE_INPUT_FILE) && defined(HAVE_FORMAT_MPEG)
            } else if (c == 'A') {
                (*subchannel)->inputProto = "file";
                (*subchannel)->type = 0;
                (*subchannel)->bitrate = 0;
                (*subchannel)->operations = dabInputMpegFileOperations;
#endif // defined(HAVE_INPUT_FILE) && defined(HAVE_FORMAT_MPEG)
#if defined(HAVE_FORMAT_DABPLUS)
            } else if (c == 'F') {
                (*subchannel)->type = 0;
                (*subchannel)->bitrate = 32;

                char* proto;

                proto = strstr(optarg, "://");
                if (proto == NULL) {
                    (*subchannel)->inputProto = "file";
                } else {
                    (*subchannel)->inputProto = optarg;
                    (*subchannel)->inputName = proto + 3;
                    *proto = 0;
                }

                if (0) {
#if defined(HAVE_INPUT_FILE)
                } else if (strcmp((*subchannel)->inputProto, "file") == 0) {
                    (*subchannel)->operations = dabInputDabplusFileOperations;
#endif // defined(HAVE_INPUT_FILE)
                } else {
                    etiLog.printHeader(TcpLog::ERR,
                            "Invalid protocol for DAB+ input (%s)\n",
                            (*subchannel)->inputProto);
                    printUsage(progName);
                    returnCode = -1;
                    goto EXIT;
                }
#endif // defined(HAVE_FORMAT_DABPLUS)
            } else if (c == 'B') {
                char* proto;

                proto = strstr(optarg, "://");
                if (proto == NULL) {
                    (*subchannel)->inputProto = "udp";
                } else {
                    (*subchannel)->inputProto = optarg;
                    (*subchannel)->inputName = proto + 3;
                    *proto = 0;
                }
                if (0) {
#if defined(HAVE_FORMAT_BRIDGE)
#if defined(HAVE_INPUT_UDP)
                } else if (strcmp((*subchannel)->inputProto, "udp") == 0) {
                    (*subchannel)->operations = dabInputBridgeUdpOperations;
#endif // defined(HAVE_INPUT_UDP)
#if defined(HAVE_INPUT_SLIP)
                } else if (strcmp((*subchannel)->inputProto, "slip") == 0) {
                    (*subchannel)->operations = dabInputSlipOperations;
#endif // defined(HAVE_INPUT_SLIP)
#endif // defined(HAVE_FORMAT_BRIDGE)
                }
            } else if (c == 'D') {
                char* proto;

                proto = strstr(optarg, "://");
                if (proto == NULL) {
                    (*subchannel)->inputProto = "udp";
                } else {
                    (*subchannel)->inputProto = optarg;
                    (*subchannel)->inputName = proto + 3;
                    *proto = 0;
                }
                if (0) {
#if defined(HAVE_INPUT_UDP)
                } else if (strcmp((*subchannel)->inputProto, "udp") == 0) {
                    (*subchannel)->operations = dabInputUdpOperations;
#endif
#if defined(HAVE_INPUT_PRBS) && defined(HAVE_FORMAT_RAW)
                } else if (strcmp((*subchannel)->inputProto, "prbs") == 0) {
                    (*subchannel)->operations = dabInputPrbsOperations;
#endif
#if defined(HAVE_INPUT_FILE) && defined(HAVE_FORMAT_RAW)
                } else if (strcmp((*subchannel)->inputProto, "file") == 0) {
                    (*subchannel)->operations = dabInputRawFileOperations;
#endif
                } else if (strcmp((*subchannel)->inputProto, "fifo") == 0) {
                    (*subchannel)->operations = dabInputRawFifoOperations;
                } else {
                    etiLog.printHeader(TcpLog::ERR,
                            "Invalid protocol for data input (%s)\n",
                            (*subchannel)->inputProto);
                    printUsage(progName);
                    returnCode = -1;
                    goto EXIT;
                }

                (*subchannel)->type = 1;
                (*subchannel)->bitrate = DEFAULT_DATA_BITRATE;
#if defined(HAVE_INPUT_TEST) && defined(HAVE_FORMAT_RAW)
            } else if (c == 'T') {
                (*subchannel)->inputProto = "test";
                (*subchannel)->type = 1;
                (*subchannel)->bitrate = DEFAULT_DATA_BITRATE;
                (*subchannel)->operations = dabInputTestOperations;
#endif // defined(HAVE_INPUT_TEST)) && defined(HAVE_FORMAT_RAW)
#ifdef HAVE_FORMAT_PACKET
            } else if (c == 'P') {
                (*subchannel)->inputProto = "file";
                (*subchannel)->type = 3;
                (*subchannel)->bitrate = DEFAULT_PACKET_BITRATE;
#ifdef HAVE_INPUT_FILE
                (*subchannel)->operations = dabInputPacketFileOperations;
#elif defined(HAVE_INPUT_FIFO)
                (*subchannel)->operations = dabInputFifoOperations;
#else
#   pragma error("Must defined at least one packet input")
#endif // defined(HAVE_INPUT_FILE)
#ifdef HAVE_FORMAT_EPM
            } else if (c == 'E') {
                (*subchannel)->inputProto = "file";
                (*subchannel)->type = 3;
                (*subchannel)->bitrate = DEFAULT_PACKET_BITRATE;
                (*subchannel)->operations = dabInputEnhancedPacketFileOperations;
#endif // defined(HAVE_FORMAT_EPM)
#endif // defined(HAVE_FORMAT_PACKET)
#ifdef HAVE_FORMAT_DMB
            } else if (c == 'M') {
                char* proto;

                proto = strstr(optarg, "://");
                if (proto == NULL) {
                    (*subchannel)->inputProto = "udp";
                } else {
                    (*subchannel)->inputProto = optarg;
                    (*subchannel)->inputName = proto + 3;
                    *proto = 0;
                }
                if (strcmp((*subchannel)->inputProto, "udp") == 0) {
                    (*subchannel)->operations = dabInputDmbUdpOperations;
                } else if (strcmp((*subchannel)->inputProto, "file") == 0) {
                    (*subchannel)->operations = dabInputDmbFileOperations;
                } else {
                    etiLog.printHeader(TcpLog::ERR,
                            "Invalid protocol for DMB input (%s)\n",
                            (*subchannel)->inputProto);
                    printUsage(progName);
                    returnCode = -1;
                    goto EXIT;
                }

                (*subchannel)->type = 1;
                (*subchannel)->bitrate = DEFAULT_DATA_BITRATE;
#endif
            } else {
                etiLog.printHeader(TcpLog::ERR,
                        "Service '%c' not yet coded!\n", c);
                returnCode = -1;
                goto EXIT;
            }
            (*subchannel)->operations.init(&(*subchannel)->data);
            for (int i = 0; i < 64; ++i) { // Find first free subchannel
                subchannel = getSubchannel(ensemble->subchannels, i);
                if (subchannel == ensemble->subchannels.end()) {
                    subchannel = ensemble->subchannels.end() - 1;
                    (*subchannel)->id = i;
                    break;
                }
            }
            (*subchannel)->startAddress = 0;

            if (c == 'A') {
                protection->form = 0;
                protection->level = 2;
                protection->shortForm.tableSwitch = 0;
                protection->shortForm.tableIndex = 0;
            } else {
                protection->level = 2;
                protection->form = 1;
                protection->longForm.option = 0;
            }
            break;
        case 'L':
            if (optarg == NULL) {
                etiLog.printHeader(TcpLog::ERR,
                        "Missing parameter for option -L\n");
                printUsage(progName);
                returnCode = -1;
                goto EXIT;
            }
            if (service == ensemble->services.end()) {
                memset(ensemble->label.text, 0, 16);
                strncpy(ensemble->label.text, optarg, 16);
                ensemble->label.flag = 0xff00;
            } else if (component != ensemble->components.end()) {
                memset((*component)->label.text, 0, 16);
                strncpy((*component)->label.text, optarg, 16);
                (*component)->label.flag = 0xff00;
            } else {    // Service
                memset((*service)->label.text, 0, 16);
                strncpy((*service)->label.text, optarg, 16);
                (*service)->label.flag = 0xff00;
            }
            // TODO Check strlen before doing short label
            // TODO Check if short label already set
            break;
        case 'V':
            goto EXIT;
        case 'l':
            if (optarg == NULL) {
                etiLog.printHeader(TcpLog::ERR,
                        "Missing parameter for option -l\n");
                printUsage(progName);
                returnCode = -1;
                goto EXIT;
            }
            if (service == ensemble->services.end()) {
                char* end;
                ensemble->label.flag = strtoul(optarg, &end, 0);
                if (*end != 0) {
                    end = optarg;
                    ensemble->label.flag = 0;
                    for (int i = 0; i < 32; ++i) {
                        if (*end == ensemble->label.text[i]) {
                            ensemble->label.flag |= 0x8000 >> i;
                            if (*(++end) == 0) {
                                break;
                            }
                        }
                    }
                    if (*end != 0) {
                        etiLog.printHeader(TcpLog::ERR,
                                "Error at '%c' in ensemble short label '%s'!\n"
                                "Not in label '%s'!\n",
                                *end, optarg, ensemble->label.text);
                        returnCode = -1;
                        goto EXIT;
                    }
                }
                int count = 0;
                for (int i = 0; i < 16; ++i) {
                    if (ensemble->label.flag & (1 << i)) {
                        ++count;
                    }
                }
                if (count > 8) {
                    etiLog.printHeader(TcpLog::ERR,
                            "Ensemble short label too long!\n"
                            "Must be < 8 characters.\n");
                    returnCode = -1;
                    goto EXIT;
                }
            } else if (component != ensemble->components.end()) {
                char* end;
                (*component)->label.flag = strtoul(optarg, &end, 0);
                if (*end != 0) {
                    end = optarg;
                    (*component)->label.flag = 0;
                    for (int i = 0; i < 32; ++i) {
                        if (*end == (*component)->label.text[i]) {
                            (*component)->label.flag |= 0x8000 >> i;
                            if (*(++end) == 0) {
                                break;
                            }
                        }
                    }
                    if (*end != 0) {
                        etiLog.printHeader(TcpLog::ERR,
                                "Error at '%c' in component short label '%s'!\n"
                                "Not in label '%s'!\n",
                                *end, optarg, (*component)->label.text);
                        returnCode = -1;
                        goto EXIT;
                    }
                }
                int count = 0;
                for (int i = 0; i < 16; ++i) {
                    if ((*component)->label.flag & (1 << i)) {
                        ++count;
                    }
                }
                if (count > 8) {
                    etiLog.printHeader(TcpLog::ERR,
                            "Service '%s' short label too long!\n"
                            "Must be < 8 characters.\n", (*component)->label.text);
                    returnCode = -1;
                    goto EXIT;
                }
            } else {
                char* end;
                (*service)->label.flag = strtoul(optarg, &end, 0);
                if (*end != 0) {
                    end = optarg;
                    (*service)->label.flag = 0;
                    for (int i = 0; i < 32; ++i) {
                        if (*end == (*service)->label.text[i]) {
                            (*service)->label.flag |= 0x8000 >> i;
                            if (*(++end) == 0) {
                                break;
                            }
                        }
                    }
                    if (*end != 0) {
                        etiLog.printHeader(TcpLog::ERR,
                                "Error at '%c' in service short label '%s'!\n"
                                "Not in label '%s'!\n",
                                *end, optarg, (*service)->label.text);
                        returnCode = -1;
                        goto EXIT;
                    }
                }
                int count = 0;
                for (int i = 0; i < 16; ++i) {
                    if ((*service)->label.flag & (1 << i)) {
                        ++count;
                    }
                }
                if (count > 8) {
                    etiLog.printHeader(TcpLog::ERR,
                            "Service '%s' short label too long!\n"
                            "Must be < 8 characters.\n", (*service)->label.text);
                    returnCode = -1;
                    goto EXIT;
                }
            }
            break;
        case 'i':
            if (optarg == NULL) {
                etiLog.printHeader(TcpLog::ERR,
                        "Missing parameter for option -i\n");
                printUsage(progName);
                returnCode = -1;
                goto EXIT;
            }
            if (component != ensemble->components.end()) {
                (*component)->subchId = strtoul(optarg, NULL, 0);
            } else if (subchannel != ensemble->subchannels.end()) {
                (*subchannel)->id = strtoul(optarg, NULL, 0);
            } else if (service != ensemble->services.end()) {
                (*service)->id = strtoul(optarg, NULL, 0);
                if ((*service)->id == 0) {
                    etiLog.printHeader(TcpLog::ERR,
                            "Service id 0 is invalid\n");
                    returnCode = -1;
                    goto EXIT;
                }
            } else {
                ensemble->id = strtoul(optarg, NULL, 0);
            }
            break;
        case 'b':
            if (optarg == NULL) {
                etiLog.printHeader(TcpLog::ERR,
                        "Missing parameter for option -b\n");
                printUsage(progName);
                returnCode = -1;
                goto EXIT;
            }
            if (subchannel == ensemble->subchannels.end()) {
                etiLog.printHeader(TcpLog::ERR,
                        "You must define a subchannel first!\n");
                printUsage(progName);
                returnCode = -1;
                goto EXIT;
            }
            (*subchannel)->bitrate = strtoul(optarg, NULL, 0);
            if (((*subchannel)->bitrate & 0x7) != 0) {
                (*subchannel)->bitrate += 8;
                (*subchannel)->bitrate &= ~0x7;
                etiLog.printHeader(TcpLog::WARNING,
                        "bitrate must be multiple of 8 -> ceiling to %i\n",
                        (*subchannel)->bitrate);
            }
            break;
        case 'c':
            if (optarg == NULL) {
                etiLog.printHeader(TcpLog::ERR,
                        "Missing parameter for option -c\n");
                printUsage(progName);
                returnCode = -1;
                goto EXIT;
            }
            ensemble->ecc = strtoul(optarg, NULL, 0);
            break;
#if defined(HAVE_INPUT_FIFO) && defined(HAVE_INPUT_FILE)
        case 'k':
            if (subchannel == ensemble->subchannels.end()) {
                etiLog.printHeader(TcpLog::ERR,
                        "You must define a subchannel first!\n");
                printUsage(progName);
                returnCode = -1;
                goto EXIT;
            }
            switch ((*subchannel)->type) {
#ifdef HAVE_FORMAT_PACKET
            case 3:
                (*subchannel)->operations.clean(&(*subchannel)->data);
                if ((*subchannel)->operations == dabInputPacketFileOperations) {
                    (*subchannel)->operations = dabInputFifoOperations;
#ifdef HAVE_FORMAT_EPM
                } else if ((*subchannel)->operations == dabInputEnhancedPacketFileOperations) {
                    (*subchannel)->operations = dabInputEnhancedFifoOperations;
#endif // defined(HAVE_FORMAT_EPM)
                } else {
                    etiLog.printHeader(TcpLog::ERR,
                            "Error, wrong packet subchannel operations!\n");
                    returnCode = -1;
                    goto EXIT;
                }
                (*subchannel)->operations.init(&(*subchannel)->data);
                (*subchannel)->inputProto = "fifo";
                break;
#endif // defined(HAVE_FORMAT_PACKET)
#ifdef HAVE_FORMAT_MPEG
            case 0:
                (*subchannel)->operations.clean(&(*subchannel)->data);
                if ((*subchannel)->operations == dabInputMpegFileOperations) {
                    (*subchannel)->operations = dabInputMpegFifoOperations;
                } else if ((*subchannel)->operations ==
                        dabInputDabplusFileOperations) {
                    (*subchannel)->operations = dabInputDabplusFifoOperations;
                } else {
                    etiLog.printHeader(TcpLog::ERR,
                            "Error, wrong audio subchannel operations!\n");
                    returnCode = -1;
                    goto EXIT;
                }
                (*subchannel)->operations.init(&(*subchannel)->data);
                (*subchannel)->inputProto = "fifo";
                break;
#endif // defined(HAVE_FORMAT_MPEG)
            default:
                etiLog.printHeader(TcpLog::ERR,
                        "sorry, non-blocking input file is "
                        "only valid with audio or packet services\n");
                returnCode = -1;
                goto EXIT;
            }
            break;
#endif // defined(HAVE_INPUT_FIFO) && defined(HAVE_INPUT_FILE)
        case 'p':
            int level;
            if (optarg == NULL) {
                etiLog.printHeader(TcpLog::ERR,
                        "Missing parameter for option -P\n");
                printUsage(progName);
                returnCode = -1;
                goto EXIT;
            }
            if (subchannel == ensemble->subchannels.end()) {
                etiLog.printHeader(TcpLog::ERR,
                        "You must define a subchannel first!\n");
                printUsage(progName);
                returnCode = -1;
                goto EXIT;
            }
            level = strtoul(optarg, NULL, 0) - 1;
            if (protection->form == 0) {
                if ((level < 0) || (level > 4)) {
                    etiLog.printHeader(TcpLog::ERR,
                            "protection level must be between "
                            "1 to 5 inclusively (current = %i)\n", level);
                    returnCode = -1;
                    goto EXIT;
                }
            } else {
                if ((level < 0) || (level > 3)) {
                    etiLog.printHeader(TcpLog::ERR,
                            "protection level must be between "
                            "1 to 4 inclusively (current = %i)\n", level);
                    returnCode = -1;
                    goto EXIT;
                }
            }
            protection->level = level;
            break;
        case 'm':
            if (optarg) {
                ensemble->mode = strtoul(optarg, NULL, 0);
                if ((ensemble->mode < 1) || (ensemble->mode > 4)) {
                    etiLog.printHeader(TcpLog::ERR,
                            "Mode must be between 1-4\n");
                    returnCode = -1;
                    goto EXIT;
                }
                if (ensemble->mode == 4)
                    ensemble->mode = 0;
                if  (ensemble->mode == 3) {
                    FICL = 32;
                } else {
                    FICL = 24;
                }
            } else {
                etiLog.printHeader(TcpLog::ERR,
                        "Missing parameter for option -m\n");
                printUsage(progName);
                returnCode = -1;
                goto EXIT;
            }
            break;
        case 'n':
            if (optarg) {
                limit = strtoul(optarg, NULL, 0);
            } else {
                etiLog.printHeader(TcpLog::ERR,
                        "Missing parameter for option -n\n");
                printUsage(progName);
                returnCode = -1;
                goto EXIT;
            }
            break;
        case 'o':
            etiLog.open("createETI", 0, 12222);
            break;
        case 't':
            if (optarg == NULL) {
                etiLog.printHeader(TcpLog::ERR,
                        "Missing parameter for option -t\n");
                printUsage(progName);
                returnCode = -1;
                goto EXIT;
            }
            if (component == ensemble->components.end()) {
                etiLog.printHeader(TcpLog::ERR,
                        "You must define a component before setting "
                        "service type!\n");
                printUsage(progName);
                returnCode = -1;
                goto EXIT;
            }
            (*component)->type = strtoul(optarg, NULL, 0);
            break;
        case 'a':
            if (component == ensemble->components.end()) {
                etiLog.printHeader(TcpLog::ERR,
                        "You must define a component before setting "
                        "packet address!\n");
                printUsage(progName);
                returnCode = -1;
                goto EXIT;
            }
            if (!(*component)->isPacketComponent(ensemble->subchannels)) {
                etiLog.printHeader(TcpLog::ERR, "address\n");
                printUsage(progName);
                returnCode = -1;
                goto EXIT;
            }
            (*component)->packet.address = strtoul(optarg, NULL, 0);
            break;
        case 'd':
            if (component == ensemble->components.end()) {
                etiLog.printHeader(TcpLog::ERR,
                        "You must define a component before setting "
                        "datagroup!\n");
                printUsage(progName);
                returnCode = -1;
                goto EXIT;
            }
            if (!(*component)->isPacketComponent(ensemble->subchannels)) {
                etiLog.printHeader(TcpLog::ERR, "datagroup\n");
                printUsage(progName);
                returnCode = -1;
                goto EXIT;
            }
            (*component)->packet.datagroup = true;
            break;
        case 'f':
            if (component == ensemble->components.end()) {
                etiLog.printHeader(TcpLog::ERR,
                        "You must define a component first!\n");
                printUsage(progName);
                returnCode = -1;
                goto EXIT;
            }
            if (!(*component)->isPacketComponent(ensemble->subchannels)) {
                etiLog.printHeader(TcpLog::ERR, "application type\n");
                printUsage(progName);
                returnCode = -1;
                goto EXIT;
            }
            (*component)->packet.appType = strtoul(optarg, NULL, 0);
            break;
        case 'g':
            if (service == ensemble->services.end()) {
                etiLog.printHeader(TcpLog::ERR, "You must define a service"
                        " before using option -%c\n", c);
                printUsage(progName);
                returnCode = -1;
                goto EXIT;
            }
            (*service)->language = strtoul(optarg, NULL, 0);
            break;
        case 's':
            {
                /*
                struct timeval tv;
                gettimeofday(&tv, NULL);
                unsigned _8ms = (tv.tv_usec / 1000) / 8;
                unsigned _1ms = (tv.tv_usec - (_8ms * 8000)) / 1000;
                unsigned _4us = 20;
                unsigned _488ns = 0;
                unsigned _61ns = 0;
                timestamp = (((((((_8ms << 3) | _1ms) << 8) | _4us) << 3) | _488ns) << 8) | _61ns;
                */
                enableTist = true;
            }
            break;
        case 'y':
            if (service == ensemble->services.end()) {
                etiLog.printHeader(TcpLog::ERR, "You must define a service"
                        " before using option -%c\n", c);
                printUsage(progName);
                returnCode = -1;
                goto EXIT;
            }
            (*service)->pty = strtoul(optarg, NULL, 0);
            break;
        case 'z':
            factumAnalyzer = true;
            break;
        case 'r':
            etiLog.printHeader(TcpLog::INFO,
                    "Enabling throttled output using simul, one frame every 24ms\n");
            outputs.push_back(new dabOutput);
            output = outputs.end() - 1;

            memset(*output, 0, sizeof(dabOutput));
            (*output)->outputProto = "simul";
            (*output)->outputName = "";
            (*output)->data = NULL;
            (*output)->operations = dabOutputDefaultOperations;

            subchannel = ensemble->subchannels.end();
            protection = NULL;
            component = ensemble->components.end();
            service = ensemble->services.end();
            break;
        case '?':
            returnCode = -1;
        case 'h':
            printUsage(progName, stdout);
            goto EXIT;
        default:
            etiLog.printHeader(TcpLog::ERR, "Option '%c' not coded yet\n", c);
            returnCode = -1;
            goto EXIT;
        }
    }
    if (optind < argc) {
        etiLog.printHeader(TcpLog::ERR, "Too much parameters:");
        while (optind < argc) {
            etiLog.printHeader(TcpLog::ERR, " %s", argv[optind++]);
        }
        etiLog.printHeader(TcpLog::ERR, "\n");
        printUsage(progName);
        returnCode = -1;
        goto EXIT;
    }

    if (outputs.size() == 0) {
        etiLog.printHeader(TcpLog::WARNING, "no output defined\n");

        outputs.push_back(new dabOutput);
        output = outputs.end() - 1;

        memset(*output, 0, sizeof(dabOutput));
        (*output)->outputProto = "simul";
        (*output)->outputName = NULL;
        (*output)->data = NULL;
        (*output)->operations = dabOutputDefaultOperations;

        printf("Press enter to continue\n");
        getchar();
    }

    // Check and adjust subchannels
    {
        set<unsigned char> ids;
        for (subchannel = ensemble->subchannels.begin();
                subchannel != ensemble->subchannels.end();
                ++subchannel) {
            if (ids.find((*subchannel)->id) != ids.end()) {
                etiLog.printHeader(TcpLog::ERR,
                        "Subchannel %u is set more than once!\n",
                        (*subchannel)->id);
                returnCode = -1;
                goto EXIT;
            }
        }
    }

    // Check and adjust services and components
    {
        set<uint32_t> ids;
        for (service = ensemble->services.begin();
                service != ensemble->services.end();
                ++service) {
            if (ids.find((*service)->id) != ids.end()) {
                etiLog.printHeader(TcpLog::ERR,
                        "Service id 0x%x (%u) is set more than once!\n",
                        (*service)->id, (*service)->id);
                returnCode = -1;
                goto EXIT;
            }

            // Get first component of this service
            component = getComponent(ensemble->components, (*service)->id);
            if (component == ensemble->components.end()) {
                etiLog.printHeader(TcpLog::ERR,
                        "Service %u includes no component!\n");
                returnCode = -1;
                goto EXIT;
            }

            // Adjust service type from this first component
            switch ((*service)->getType(ensemble)) {
            case 0: // Audio
                (*service)->program = true;
                break;
            case 1:
            case 2:
            case 3:
                (*service)->program = false;
                break;
            default:
                etiLog.printHeader(TcpLog::ERR,
                        "Error, unknown service type: %u\n", (*service)->getType(ensemble));
                returnCode = -1;
                goto EXIT;
            }

            // Adjust components type for DAB+
            while (component != ensemble->components.end()) {
                subchannel =
                    getSubchannel(ensemble->subchannels, (*component)->subchId);
                if (subchannel == ensemble->subchannels.end()) {
                    etiLog.printHeader(TcpLog::ERR, "Error, service %u component "
                            "links to the invalid subchannel %u\n",
                            (*component)->serviceId, (*component)->subchId);
                    returnCode = -1;
                    goto EXIT;
                }

                protection = &(*subchannel)->protection;
                switch ((*subchannel)->type) {
                case 0: // Audio
                    {
                        if (protection->form != 0) {
                            (*component)->type = 0x3f;  // DAB+
                        }
                    }
                    break;
                case 1:
                case 2:
                case 3:
                    break;
                default:
                    etiLog.printHeader(TcpLog::ERR,
                            "Error, unknown subchannel type\n");
                    returnCode = -1;
                    goto EXIT;
                }
                component = getComponent(ensemble->components,
                        (*service)->id, component);
            }
        }
    }


    for (output = outputs.begin(); output != outputs.end() ; ++output) {
#if defined(HAVE_OUTPUT_FILE)
        if (strcmp((*output)->outputProto, "file") == 0) {
            (*output)->operations = dabOutputFileOperations;
#else // !defined(HAVE_OUTPUT_FILE)
        if (0) {
#endif // defined(HAVE_OUTPUT_FILE)
#if defined(HAVE_OUTPUT_FIFO)
        } else if (strcmp((*output)->outputProto, "fifo") == 0) {
            (*output)->operations = dabOutputFifoOperations;
#endif // !defined(HAVE_OUTPUT_FIFO)
#if defined(HAVE_OUTPUT_RAW)
        } else if (strcmp((*output)->outputProto, "raw") == 0) {
            (*output)->operations = dabOutputRawOperations;
#endif // defined(HAVE_OUTPUT_RAW)
#if defined(HAVE_OUTPUT_UDP)
        } else if (strcmp((*output)->outputProto, "udp") == 0) {
            (*output)->operations = dabOutputUdpOperations;
#endif // defined(HAVE_OUTPUT_UDP)
#if defined(HAVE_OUTPUT_TCP)
        } else if (strcmp((*output)->outputProto, "tcp") == 0) {
            (*output)->operations = dabOutputTcpOperations;
#endif // defined(HAVE_OUTPUT_TCP)
#if defined(HAVE_OUTPUT_SIMUL)
        } else if (strcmp((*output)->outputProto, "simul") == 0) {
            (*output)->operations = dabOutputSimulOperations;
#endif // defined(HAVE_OUTPUT_SIMUL)
        } else {
            etiLog.printHeader(TcpLog::ERR, "Output protcol unknown: %s\n",
                    (*output)->outputProto);
            goto EXIT;
        }

        if ((*output)->operations.init(&(*output)->data) == -1) {
            etiLog.printHeader(TcpLog::ERR, "Unable to init output %s://%s\n",
                    (*output)->outputProto, (*output)->outputName);
            return -1;
        }
        if ((*output)->operations.open((*output)->data, (*output)->outputName)
                == -1) {
            etiLog.printHeader(TcpLog::ERR, "Unable to open output %s://%s\n",
                    (*output)->outputProto, (*output)->outputName);
            return -1;
        }
    }

    //Relatif aux fichiers d'entre
    for (subchannel = ensemble->subchannels.begin();
            subchannel != ensemble->subchannels.end();
            ++subchannel) {
        protection = &(*subchannel)->protection;
        if (subchannel == ensemble->subchannels.begin()) {
            (*subchannel)->startAddress = 0;
        } else {
            (*subchannel)->startAddress = (*(subchannel - 1))->startAddress +
                getSizeCu(*(subchannel - 1));
        }
        if ((*subchannel)->operations.open((*subchannel)->data,
                    (*subchannel)->inputName) == -1) {
            perror((*subchannel)->inputName);
            returnCode = -1;
            goto EXIT;
        }

        // TODO Check errors
        int result = (*subchannel)->operations.setBitrate(
                &(*subchannel)->operations, (*subchannel)->data,
                (*subchannel)->bitrate);
        if (result <= 0) {
            etiLog.printHeader(TcpLog::ERR, "can't set bitrate for source %s\n",
                    (*subchannel)->inputName);
            returnCode = -1;
            goto EXIT;
        }
        (*subchannel)->bitrate = result;

        if (protection->form == 0) {
            protection->form = 1;
            for (int i = 0; i < 64; i++) {
                if ((*subchannel)->bitrate == BitRateTable[i]) {
                    if (protection->level == ProtectionLevelTable[i]) {
                        protection->form = 0;
                        protection->shortForm.tableIndex = i;
                    }
                }
            }
        }
    }

    if (ensemble->subchannels.size() == 0) {
        etiLog.printHeader(TcpLog::ERR, "can't multiplexed no subchannel!\n");
        returnCode = -1;
        goto EXIT;
    }

    subchannel = ensemble->subchannels.end() - 1;
    if ((*subchannel)->startAddress + getSizeCu((*subchannel)) > 864) {
        etiLog.printHeader(TcpLog::ERR, "Total size in CU exceeds 864\n");
        printSubchannels(ensemble->subchannels);
        returnCode = -1;
        goto EXIT;
    }

    // Init packet components SCId
    cur = 0;
    for (component = ensemble->components.begin();
            component != ensemble->components.end();
            ++component) {
        subchannel = getSubchannel(ensemble->subchannels,
                (*component)->subchId);
        if (subchannel == ensemble->subchannels.end()) {
            etiLog.printHeader(TcpLog::ERR,
                    "Subchannel %i does not exist for component "
                    "of service %i\n",
                    (*component)->subchId, (*component)->serviceId);
            returnCode = -1;
            goto EXIT;
        }
        if ((*subchannel)->type != 3) continue;

        (*component)->packet.id = cur++;
    }

    //Initialisation a 0 des cases de la trame ETI
    memset(etiFrame, 0, 6144);

    // Print settings before starting
    etiLog.printHeader(TcpLog::INFO, "\n--- Multiplex configuration ---\n");
    printEnsemble(ensemble);

    etiLog.printHeader(TcpLog::INFO, "\n--- Subchannels list ---\n");
    printSubchannels(ensemble->subchannels);

    etiLog.printHeader(TcpLog::INFO, "\n--- Services list ---\n");
    printServices(ensemble->services);

    etiLog.printHeader(TcpLog::INFO, "\n--- Components list ---\n");
    printComponents(ensemble->components);

    etiLog.printHeader(TcpLog::INFO, "\n--- Output list ---\n");
    printOutputs(outputs);

    etiLog.printHeader(TcpLog::INFO, "\n");


    /***************************************************************************
     **********   Boucle principale, chaque passage cree une trame  ************
     **************************************************************************/
    serviceProgramInd = ensemble->services.end();
    serviceDataInd = ensemble->services.end();
    componentIndicatorProgram = ensemble->components.end();
    componentIndicatorData = ensemble->components.end();
    servicePty = ensemble->services.end();
    subchannelIndicator = ensemble->subchannels.end();


    for (currentFrame = 0; running; currentFrame++) {
        if ((limit > 0) && (currentFrame >= limit)) {
            break;
        }
        date = getDabTime();

        //Initialisation a 0 des cases de la trame
        memset(etiFrame, 0, 6144);

        /**********************************************************************
         **********   Section SYNC du ETI(NI, G703)   *************************
         **********************************************************************/

        //declare une instance d'une structure eti_SYNC
        eti_SYNC *etiSync = (eti_SYNC *) etiFrame;    
        //****** Section ERR ******//
        // 1 octet
        etiSync->ERR = 0xFF;    //Indique qu'il n'y a pas d'erreur
        //****** Section FSYNC *****//
        // 3 octets, pour la synchronisation, alterne a chaque trame entre les
        // deux symboles
        sync ^= 0xffffff;
        etiSync->FSYNC = sync;

        /**********************************************************************
         ***********   Section LIDATA du ETI(NI, G703)   **********************
         **********************************************************************/

        //****** Section FC ***************************************************/
        // 4 octets
        // declare une instance d une structure eti_FC et la place dans la trame
        eti_FC *fc = (eti_FC *) & etiFrame[4];

        //****** FCT **********************//
        //Incremente a chaque trame, de 0 a 249, 1 octet
        fc->FCT = currentFrame % 250;

        //****** FICF ******//
        //Fast Information Channel Flag, 1 bit, =1 si le FIC est present
        fc->FICF = 1;

        //****** NST ******//
        //Number of Stream, 7 bits,  0-64, 0 si reconfiguration du multiplex
        fc->NST = ensemble->subchannels.size();

        //****** FP ******//
        // Frame Phase, 3 bits, compteur sur 3 bits, permet au COFDM generator
        // de savoir quand inserer le TII utilise egalement par le MNSC
        fc->FP = currentFrame & 0x7;

        //****** MID ******//
        //Mode Identity, 2 bits, 01 ModeI, 10 modeII, 11 ModeIII, 00 ModeIV
        fc->MID = ensemble->mode;      //mode 2 demande 3 FIB, 3*32octets = 96octets

        //****** FL ******//
        //Frame Length, 11 bits, nb of words(4 bytes) in STC, EOH and MST  
        // si NST=0, FL=1+FICL words, FICL=24 ou 32 selon le mode
        //en word ( 4 bytes), +1 pour la partie EOH
        FLtmp = 1 + FICL + (fc->NST);

        for (subchannel = ensemble->subchannels.begin();
                subchannel != ensemble->subchannels.end();
                ++subchannel) {
            //Taille d'une trame audio mp2 en paquet de 64 bits
            FLtmp += getSizeWord(*subchannel);
        }

        fc->setFrameLength(FLtmp);
        index = 8;

        /******* Section STC **************************************************/
        // Stream Characterization,
        //  number of channel * 4 octets = nb octets total
        for (subchannel = ensemble->subchannels.begin();
                subchannel != ensemble->subchannels.end();
                ++subchannel) {
            protection = &(*subchannel)->protection;
            eti_STC *sstc = (eti_STC *) & etiFrame[index];

            sstc->SCID = (*subchannel)->id;
            sstc->startAddress_high = (*subchannel)->startAddress / 256;
            sstc->startAddress_low = (*subchannel)->startAddress % 256;
            //devrait changer selon le mode de protection desire
            if (protection->form == 0) {
                sstc->TPL = 0x10 |
                    ProtectionLevelTable[protection->shortForm.tableIndex];
            } else {
                sstc->TPL = 0x20 |
                    (protection->longForm.option << 2) |
                    (protection->level);
            }
            //Sub-channel Stream Length, multiple de 64 bits 
            sstc->STL_high = getSizeDWord(*subchannel) / 256;
            sstc->STL_low = getSizeDWord(*subchannel) % 256;
            index += 4;
        }

        /******* Section EOH **************************************************/
        // End of Header 4 octets
        eti_EOH *eoh = (eti_EOH *) & etiFrame[index];

        //MNSC Multiplex Network Signalling Channel, 2 octets

        eoh->MNSC = 0;

        struct tm *time_tm = gmtime(&mnsc_time.tv_sec);
        switch (fc->FP & 0x3)
        {
            case 0:
                if (MNSC_increment_time)
                {
                    MNSC_increment_time = false;
                    mnsc_time.tv_sec += 1;
                }
                {

                    eti_MNSC_TIME_0 *mnsc = (eti_MNSC_TIME_0 *) &eoh->MNSC;
                    // Set fields according to ETS 300 799 -- 5.5.1 and A.2.2 
                    mnsc->type = 0;
                    mnsc->identifier = 0;
                    mnsc->rfa = 0;
                }
                break;
            case 1:
                {
                    eti_MNSC_TIME_1 *mnsc = (eti_MNSC_TIME_1 *) &eoh->MNSC;
                    mnsc->setFromTime(time_tm);
                    mnsc->accuracy = 1;
                    mnsc->sync_to_frame = 1;
                }
                break;
            case 2:
                {
                    eti_MNSC_TIME_2 *mnsc = (eti_MNSC_TIME_2 *) &eoh->MNSC;
                    mnsc->setFromTime(time_tm);
                }
                break;
            case 3:
                {
                    eti_MNSC_TIME_3 *mnsc = (eti_MNSC_TIME_3 *) &eoh->MNSC;
                    mnsc->setFromTime(time_tm);
                }
                break;
        }


        //CRC Cyclic Redundancy Checksum du FC,  STC et MNSC, 2 octets
        nbBytesCRC = 4 + ((fc->NST) * 4) + 2;

        CRCtmp = 0xffff;
        CRCtmp = crc16(CRCtmp, &etiFrame[4], nbBytesCRC);
        CRCtmp ^= 0xffff;
        eoh->CRC = htons(CRCtmp);

        /******* Section MST **************************************************/
        // Main Stream Data, si FICF=1 alors les 96 ou 128 premiers octets
        // transportent le FIC selon le mode
        index = ((fc->NST) + 2 + 1) * 4;

        //Insertion du FIC
        FIGtype0* fig0;
        FIGtype0_0 *fig0_0;
        FIGtype0_1 *figtype0_1;

        FIG_01_SubChannel_ShortF *fig0_1subchShort;
        FIG_01_SubChannel_LongF *fig0_1subchLong1;

        FIGtype0_2 *fig0_2;

        FIGtype0_2_Service *fig0_2serviceAudio;
        FIGtype0_2_Service_data *fig0_2serviceData;
        FIGtype0_2_audio_component* audio_description;
        FIGtype0_2_data_component* data_description;
        FIGtype0_2_packet_component* packet_description;

        FIGtype0_3_header *fig0_3_header;
        FIGtype0_3_data *fig0_3_data;
        FIGtype0_9 *fig0_9;
        FIGtype0_10 *fig0_10;
        FIGtype0_17_programme *programme;

        FIGtype1_0 *fig1_0;
        FIGtype1_1 *fig1_1;
        FIGtype1_5 *fig1_5;

        tm* timeData;

        unsigned char figSize = 0;

        //Insertion du FIB 0
        switch (insertFIG) {

        case 0:
        case 4:
            // FIG type 0/0, Multiplex Configuration Info (MCI),
            //  Ensemble information
            fig0_0 = (FIGtype0_0 *) & etiFrame[index];

            fig0_0->FIGtypeNumber = 0;
            fig0_0->Length = 5;
            fig0_0->CN = 0;
            fig0_0->OE = 0;
            fig0_0->PD = 0;
            fig0_0->Extension = 0;

            fig0_0->EId = htons(ensemble->id);
            fig0_0->Change = 0;
            fig0_0->Al = 0;
            fig0_0->CIFcnt_hight = (currentFrame / 250) % 20;
            fig0_0->CIFcnt_low = (currentFrame % 250);
            index = index + 6;
            figSize += 6;

            break;

        case 1:
            // FIG type 0/1, MIC, Sub-Channel Organization, une instance de la
            // sous-partie par sous-canal
            figtype0_1 = (FIGtype0_1 *) & etiFrame[index];

            figtype0_1->FIGtypeNumber = 0;
            figtype0_1->Length = 1;
            figtype0_1->CN = 0;
            figtype0_1->OE = 0;
            figtype0_1->PD = 0;
            figtype0_1->Extension = 1;
            index = index + 2;
            figSize += 2;

            //Sous-partie du FIG type 0/1
            if (subchannelIndicator == ensemble->subchannels.end()) {
                subchannelIndicator = ensemble->subchannels.begin();
            }
            for (; subchannelIndicator != ensemble->subchannels.end();
                    ++subchannelIndicator) {
                protection = &(*subchannelIndicator)->protection;

                if ((protection->form == 0 && figSize > 27) ||
                        (protection->form != 0 && figSize > 26)) {
                    break;
                }

                if (protection->form == 0) {
                    fig0_1subchShort =
                        (FIG_01_SubChannel_ShortF*) &etiFrame[index];
                    fig0_1subchShort->SubChId = (*subchannelIndicator)->id;
                    fig0_1subchShort->StartAdress_high =
                        (*subchannelIndicator)->startAddress / 256;
                    fig0_1subchShort->StartAdress_low =
                        (*subchannelIndicator)->startAddress % 256;
                    fig0_1subchShort->Short_Long_form = 0;
                    fig0_1subchShort->TableSwitch = 0;
                    fig0_1subchShort->TableIndex =
                        protection->shortForm.tableIndex;

                    index = index + 3;
                    figSize += 3;
                    figtype0_1->Length += 3;
                } else {
                    fig0_1subchLong1 =
                        (FIG_01_SubChannel_LongF*) &etiFrame[index];
                    fig0_1subchLong1->SubChId = (*subchannelIndicator)->id;
                    fig0_1subchLong1->StartAdress_high =
                        (*subchannelIndicator)->startAddress / 256;
                    fig0_1subchLong1->StartAdress_low =
                        (*subchannelIndicator)->startAddress % 256;
                    fig0_1subchLong1->Short_Long_form = 1;
                    fig0_1subchLong1->Option = protection->longForm.option;
                    fig0_1subchLong1->ProtectionLevel =
                        protection->level;
                    fig0_1subchLong1->Sub_ChannelSize_high =
                        getSizeCu(*subchannelIndicator) / 256;
                    fig0_1subchLong1->Sub_ChannelSize_low =
                        getSizeCu(*subchannelIndicator) % 256;

                    index = index + 4;
                    figSize += 4;
                    figtype0_1->Length += 4;
                }
            }
            break;

        case 2:
            // FIG type 0/2, MCI, Service Organization, une instance de
            // FIGtype0_2_Service par sous-canal
            fig0_2 = NULL;
            cur = 0;

            if (serviceProgramInd == ensemble->services.end()) {
                serviceProgramInd = ensemble->services.begin();
            }
            for (; serviceProgramInd != ensemble->services.end();
                    ++serviceProgramInd) {
                if (!(*serviceProgramInd)->nbComponent(ensemble->components)) {
                    continue;
                }
                if ((*serviceProgramInd)->getType(ensemble) != 0) {
                    continue;
                }

                ++cur;

                if (fig0_2 == NULL) {
                    fig0_2 = (FIGtype0_2 *) & etiFrame[index];

                    fig0_2->FIGtypeNumber = 0;
                    fig0_2->Length = 1;
                    fig0_2->CN = 0;
                    fig0_2->OE = 0;
                    fig0_2->PD = 0;
                    fig0_2->Extension = 2;
                    index = index + 2;
                    figSize += 2;
                }

                if (figSize + 3
                        + (*serviceProgramInd)->nbComponent(ensemble->components)
                        * 2 > 30) {
                    break;
                }

                fig0_2serviceAudio = (FIGtype0_2_Service*) &etiFrame[index];

                fig0_2serviceAudio->SId = htons((*serviceProgramInd)->id);
                fig0_2serviceAudio->Local_flag = 0;
                fig0_2serviceAudio->CAId = 0;
                fig0_2serviceAudio->NbServiceComp =
                    (*serviceProgramInd)->nbComponent(ensemble->components);
                index += 3;
                fig0_2->Length += 3;
                figSize += 3;

                int curCpnt = 0;
                for (component = getComponent(ensemble->components,
                            (*serviceProgramInd)->id);
                        component != ensemble->components.end();
                        component = getComponent(ensemble->components,
                            (*serviceProgramInd)->id, component)) {
                    subchannel = getSubchannel(ensemble->subchannels,
                            (*component)->subchId);
                    if (subchannel == ensemble->subchannels.end()) {
                        etiLog.printHeader(TcpLog::ERR,
                                "Subchannel %i does not exist for component "
                                "of service %i\n",
                                (*component)->subchId, (*component)->serviceId);
                        returnCode = -1;
                        goto EXIT;
                    }

                    switch ((*subchannel)->type) {
                    case 0: // Audio
                        audio_description =
                            (FIGtype0_2_audio_component*)&etiFrame[index];
                        audio_description->TMid = 0;
                        audio_description->ASCTy = (*component)->type;
                        audio_description->SubChId = (*subchannel)->id;
                        audio_description->PS = ((curCpnt == 0) ? 1 : 0);
                        audio_description->CA_flag = 0;
                        break;
                    case 1: // Data
                        data_description =
                            (FIGtype0_2_data_component*)&etiFrame[index];
                        data_description->TMid = 1;
                        data_description->DSCTy = (*component)->type;
                        data_description->SubChId = (*subchannel)->id;
                        data_description->PS = ((curCpnt == 0) ? 1 : 0);
                        data_description->CA_flag = 0;
                        break;
                    case 3: // Packet
                        packet_description =
                            (FIGtype0_2_packet_component*)&etiFrame[index];
                        packet_description->TMid = 3;
                        packet_description->setSCId((*component)->packet.id);
                        packet_description->PS = ((curCpnt == 0) ? 1 : 0);
                        packet_description->CA_flag = 0;
                        break;
                    default:
                        etiLog.printHeader(TcpLog::ERR,
                                "Component type not supported\n");
                        returnCode = -1;
                        goto EXIT;
                    }
                    index += 2;
                    fig0_2->Length += 2;
                    figSize += 2;
                    if (figSize > 30) {
                        etiLog.printHeader(TcpLog::ERR,
                                "Sorry, no place left in FIG 0/2 to insert "
                                "component %i of program service %i.\n",
                                curCpnt, cur);
                        returnCode = -1;
                        goto EXIT;
                    }
                    ++curCpnt;
                }
            }
            break;

        case 3:
            fig0_2 = NULL;
            cur = 0;

            if (serviceDataInd == ensemble->services.end()) {
                serviceDataInd = ensemble->services.begin();
            }
            for (; serviceDataInd != ensemble->services.end();
                    ++serviceDataInd) {
                if (!(*serviceDataInd)->nbComponent(ensemble->components)) {
                    continue;
                }
                unsigned char type = (*serviceDataInd)->getType(ensemble);
                if ((type == 0) || (type == 2)) {
                    continue;
                }

                ++cur;

                if (fig0_2 == NULL) {
                    fig0_2 = (FIGtype0_2 *) & etiFrame[index];

                    fig0_2->FIGtypeNumber = 0;
                    fig0_2->Length = 1;
                    fig0_2->CN = 0;
                    fig0_2->OE = 0;
                    fig0_2->PD = 1;
                    fig0_2->Extension = 2;
                    index = index + 2;
                    figSize += 2;
                }

                if (figSize + 5
                        + (*serviceDataInd)->nbComponent(ensemble->components)
                        * 2 > 30) {
                    break;
                }

                fig0_2serviceData =
                    (FIGtype0_2_Service_data*) &etiFrame[index];

                fig0_2serviceData->SId = htonl((*serviceDataInd)->id);
                fig0_2serviceData->Local_flag = 0;
                fig0_2serviceData->CAId = 0;
                fig0_2serviceData->NbServiceComp =
                    (*serviceDataInd)->nbComponent(ensemble->components);
                fig0_2->Length += 5;
                index += 5;
                figSize += 5;

                int curCpnt = 0;
                for (component = getComponent(ensemble->components,
                            (*serviceDataInd)->id);
                        component != ensemble->components.end();
                        component = getComponent(ensemble->components,
                            (*serviceDataInd)->id, component)) {
                    subchannel = getSubchannel(ensemble->subchannels,
                            (*component)->subchId);
                    if (subchannel == ensemble->subchannels.end()) {
                        etiLog.printHeader(TcpLog::ERR,
                                "Subchannel %i does not exist for component "
                                "of service %i\n",
                                (*component)->subchId, (*component)->serviceId);
                        returnCode = -1;
                        goto EXIT;
                    }

                    switch ((*subchannel)->type) {
                    case 0: // Audio
                        audio_description =
                            (FIGtype0_2_audio_component*)&etiFrame[index];
                        audio_description->TMid = 0;
                        audio_description->ASCTy = (*component)->type;
                        audio_description->SubChId = (*subchannel)->id;
                        audio_description->PS = ((curCpnt == 0) ? 1 : 0);
                        audio_description->CA_flag = 0;
                        break;
                    case 1: // Data
                        data_description =
                            (FIGtype0_2_data_component*)&etiFrame[index];
                        data_description->TMid = 1;
                        data_description->DSCTy = (*component)->type;
                        data_description->SubChId = (*subchannel)->id;
                        data_description->PS = ((curCpnt == 0) ? 1 : 0);
                        data_description->CA_flag = 0;
                        break;
                    case 3: // Packet
                        packet_description =
                            (FIGtype0_2_packet_component*)&etiFrame[index];
                        packet_description->TMid = 3;
                        packet_description->setSCId((*component)->packet.id);
                        packet_description->PS = ((curCpnt == 0) ? 1 : 0);
                        packet_description->CA_flag = 0;
                        break;
                    default:
                        etiLog.printHeader(TcpLog::ERR,
                                "Component type not supported\n");
                        returnCode = -1;
                        goto EXIT;
                    }
                    index += 2;
                    fig0_2->Length += 2;
                    figSize += 2;
                    if (figSize > 30) {
                        etiLog.printHeader(TcpLog::ERR,
                                "Sorry, no place left in FIG 0/2 to insert "
                                "component %i of data service %i.\n",
                                curCpnt, cur);
                        returnCode = -1;
                        goto EXIT;
                    }
                    ++curCpnt;
                }
            }
            break;

        case 5:
            fig0_3_header = NULL;

            for (component = ensemble->components.begin();
                    component != ensemble->components.end();
                    ++component) {
                subchannel = getSubchannel(ensemble->subchannels,
                        (*component)->subchId);
                if (subchannel == ensemble->subchannels.end()) {
                    etiLog.printHeader(TcpLog::ERR,
                            "Subchannel %i does not exist for component "
                            "of service %i\n",
                            (*component)->subchId, (*component)->serviceId);
                    returnCode = -1;
                    goto EXIT;
                }

                if ((*subchannel)->type != 3) continue;

                if (fig0_3_header == NULL) {
                    fig0_3_header = (FIGtype0_3_header*)&etiFrame[index];
                    fig0_3_header->FIGtypeNumber = 0;
                    fig0_3_header->Length = 1;
                    fig0_3_header->CN = 0;
                    fig0_3_header->OE = 0;
                    fig0_3_header->PD = 0;
                    fig0_3_header->Extension = 3;

                    index += 2;
                    figSize += 2;
                }

                /*  Warning: When bit SCCA_flag is unset(0), the multiplexer
                 *  R&S does not send the SCCA field. But, in the Factum ETI
                 *  analyzer, if this field is not there, it is an error.
                 */
                fig0_3_data = (FIGtype0_3_data*)&etiFrame[index];
                fig0_3_data->setSCId((*component)->packet.id);
                fig0_3_data->rfa = 0;
                fig0_3_data->SCCA_flag = 0;
                // if 0, datagroups are used
                fig0_3_data->DG_flag = !(*component)->packet.datagroup;
                fig0_3_data->rfu = 0;
                fig0_3_data->DSCTy = (*component)->type;
                fig0_3_data->SubChId = (*subchannel)->id;
                fig0_3_data->setPacketAddress((*component)->packet.address);
                if (factumAnalyzer) {
                    fig0_3_data->SCCA = 0;
                }

                fig0_3_header->Length += 5;
                index += 5;
                figSize += 5;
                if (factumAnalyzer) {
                    fig0_3_header->Length += 2;
                    index += 2;
                    figSize += 2;
                }

                if (figSize > 30) {
                    etiLog.printHeader(TcpLog::ERR,
                            "can't add to Fic Fig 0/3, "
                            "too much packet service\n");
                    returnCode = -1;
                    goto EXIT;
                }
            }
            break;

        case 7:
            fig0 = NULL;
            if (servicePty == ensemble->services.end()) {
                servicePty = ensemble->services.begin();
            }
            for (; servicePty != ensemble->services.end();
                    ++servicePty) {
                if ((*servicePty)->pty == 0 && (*servicePty)->language == 0) {
                    continue;
                }
                if (fig0 == NULL) {
                    fig0 = (FIGtype0*)&etiFrame[index];
                    fig0->FIGtypeNumber = 0;
                    fig0->Length = 1;
                    fig0->CN = 0;
                    fig0->OE = 0;
                    fig0->PD = 0;
                    fig0->Extension = 17;
                    index += 2;
                    figSize += 2;
                }

                if ((*servicePty)->language == 0) {
                    if (figSize + 4 > 30) {
                        break;
                    }
                } else {
                    if (figSize + 5 > 30) {
                        break;
                    }
                }

                programme = 
                    (FIGtype0_17_programme*)&etiFrame[index];
                programme->SId = htons((*servicePty)->id);
                programme->SD = 1;
                programme->PS = 0;
                programme->L = (*servicePty)->language != 0;
                programme->CC = 0;
                programme->Rfa = 0;
                programme->NFC = 0;
                if ((*servicePty)->language == 0) {
                    etiFrame[index + 3] = (*servicePty)->pty;
                    fig0->Length += 4;
                    index += 4;
                    figSize += 4;
                } else {
                    etiFrame[index + 3] = (*servicePty)->language;
                    etiFrame[index + 4] = (*servicePty)->pty;
                    fig0->Length += 5;
                    index += 5;
                    figSize += 5;
                }
            }
            break;
        }

        if (figSize > 30) {
            etiLog.printHeader(TcpLog::ERR,
                    "FIG too big (%i > 30)\n", figSize);
            returnCode = -1;
            goto EXIT;
        }

        memcpy(&etiFrame[index], Padding_FIB, 30 - figSize);
        index += 30 - figSize;

        CRCtmp = 0xffff;
        CRCtmp = crc16(CRCtmp, &etiFrame[(index - 30)], 30);
        CRCtmp ^= 0xffff;
        etiFrame[index++] = ((char *) &CRCtmp)[1];
        etiFrame[index++] = ((char *) &CRCtmp)[0];

        figSize = 0;
        // Insertion du FIB 1        
        switch (alterneFIB) {
        case 0:     // FIG 0/8 program
            fig0 = NULL;

            if (componentIndicatorProgram == ensemble->components.end()) {
                componentIndicatorProgram = ensemble->components.begin();
            }
            for (; componentIndicatorProgram != ensemble->components.end();
                    ++componentIndicatorProgram) {
                service = getService(*componentIndicatorProgram,
                        ensemble->services);
                subchannel = getSubchannel(ensemble->subchannels,
                        (*componentIndicatorProgram)->subchId);
                if (subchannel == ensemble->subchannels.end()) {
                    etiLog.printHeader(TcpLog::ERR,
                            "Subchannel %i does not exist for component "
                            "of service %i\n",
                            (*componentIndicatorProgram)->subchId,
                            (*componentIndicatorProgram)->serviceId);
                    returnCode = -1;
                    goto EXIT;
                }

                if (!(*service)->program) continue;

                if (fig0 == NULL) {
                    fig0 = (FIGtype0*)&etiFrame[index];
                    fig0->FIGtypeNumber = 0;
                    fig0->Length = 1;
                    fig0->CN = 0;
                    fig0->OE = 0;
                    fig0->PD = 0;
                    fig0->Extension = 8;
                    index += 2;
                    figSize += 2;
                }

                if ((*subchannel)->type == 3) { // Data packet
                    if (figSize > 30 - 5) {
                        break;
                    }
                    *((uint16_t*)&etiFrame[index]) =
                        htons((*componentIndicatorProgram)->serviceId);
                    fig0->Length += 2;
                    index += 2;
                    figSize += 2;

                    FIGtype0_8_long* definition =
                        (FIGtype0_8_long*)&etiFrame[index];
                    memset(definition, 0, 3);
                    definition->ext = 0;    // no rfa
                    definition->SCIdS = (*componentIndicatorProgram)->SCIdS;
                    definition->LS = 1;
                    definition->setSCId((*componentIndicatorProgram)->packet.id);
                    fig0->Length += 3;
                    index += 3;             // 8 minus rfa
                    figSize += 3;
                } else {    // Audio, data stream or FIDC
                    if (figSize > 30 - 4) {
                        break;
                    }
                    *((uint16_t*)&etiFrame[index]) =
                        htons((*componentIndicatorProgram)->serviceId);
                    fig0->Length += 2;
                    index += 2;
                    figSize += 2;

                    FIGtype0_8_short* definition =
                        (FIGtype0_8_short*)&etiFrame[index];
                    memset(definition, 0, 2);
                    definition->ext = 0;    // no rfa
                    definition->SCIdS = (*componentIndicatorProgram)->SCIdS;
                    definition->LS = 0;
                    definition->MscFic = 0;
                    definition->Id = (*componentIndicatorProgram)->subchId;
                    fig0->Length += 2;
                    index += 2;             // 4 minus rfa
                    figSize += 2;
                }
            }
            break;

        case 1:     // FIG 0/8 data
            fig0 = NULL;

            if (componentIndicatorData == ensemble->components.end()) {
                componentIndicatorData = ensemble->components.begin();
            }
            for (; componentIndicatorData != ensemble->components.end();
                    ++componentIndicatorData) {
                service = getService(*componentIndicatorData,
                        ensemble->services);
                subchannel = getSubchannel(ensemble->subchannels,
                        (*componentIndicatorData)->subchId);
                if (subchannel == ensemble->subchannels.end()) {
                    etiLog.printHeader(TcpLog::ERR,
                            "Subchannel %i does not exist for component "
                            "of service %i\n",
                            (*componentIndicatorData)->subchId,
                            (*componentIndicatorData)->serviceId);
                    returnCode = -1;
                    goto EXIT;
                }

                if ((*service)->program) continue;

                if (fig0 == NULL) {
                    fig0 = (FIGtype0*)&etiFrame[index];
                    fig0->FIGtypeNumber = 0;
                    fig0->Length = 1;
                    fig0->CN = 0;
                    fig0->OE = 0;
                    fig0->PD = 1;
                    fig0->Extension = 8;
                    index += 2;
                    figSize += 2;
                }

                if ((*subchannel)->type == 3) { // Data packet
                    if (figSize > 30 - 7) {
                        break;
                    }
                    *((uint32_t*)&etiFrame[index]) =
                        htonl((*componentIndicatorData)->serviceId);
                    fig0->Length += 4;
                    index += 4;
                    figSize += 4;

                    FIGtype0_8_long* definition =
                        (FIGtype0_8_long*)&etiFrame[index];
                    memset(definition, 0, 3);
                    definition->ext = 0;    // no rfa
                    definition->SCIdS = (*componentIndicatorData)->SCIdS;
                    definition->LS = 1;
                    definition->setSCId((*componentIndicatorData)->packet.id);
                    fig0->Length += 3;
                    index += 3;             // 8 minus rfa
                    figSize += 3;
                } else {    // Audio, data stream or FIDC
                    if (figSize > 30 - 6) {
                        break;
                    }
                    *((uint32_t*)&etiFrame[index]) =
                        htonl((*componentIndicatorData)->serviceId);
                    fig0->Length += 4;
                    index += 4;
                    figSize += 4;

                    FIGtype0_8_short* definition =
                        (FIGtype0_8_short*)&etiFrame[index];
                    memset(definition, 0, 2);
                    definition->ext = 0;    // no rfa
                    definition->SCIdS = (*componentIndicatorData)->SCIdS;
                    definition->LS = 0;
                    definition->MscFic = 0;
                    definition->Id = (*componentIndicatorData)->subchId;
                    fig0->Length += 2;
                    index += 2;             // 4 minus rfa
                    figSize += 2;
                }
            }
            break;

        case 3:
            // FIG type 1/0, Service Information (SI), Ensemble Label
            fig1_0 = (FIGtype1_0 *) & etiFrame[index];

            fig1_0->Length = 21;
            fig1_0->FIGtypeNumber = 1;
            fig1_0->Extension = 0;
            fig1_0->OE = 0;
            fig1_0->Charset = 0;
            fig1_0->EId = htons(ensemble->id);
            index = index + 4;

            memcpy(&etiFrame[index], ensemble->label.text, 16);
            index = index + 16;

            etiFrame[index++] = ((char *) &ensemble->label.flag)[1];
            etiFrame[index++] = ((char *) &ensemble->label.flag)[0];

            figSize += 22;
            break;
        case 5:
            // FIG 0 / 13
            fig0 = NULL;

            for (component = ensemble->components.begin();
                    component != ensemble->components.end();
                    ++component) {
                subchannel = getSubchannel(ensemble->subchannels,
                        (*component)->subchId);
                if (subchannel == ensemble->subchannels.end()) {
                    etiLog.printHeader(TcpLog::ERR,
                            "Subchannel %i does not exist for component "
                            "of service %i\n",
                            (*component)->subchId, (*component)->serviceId);
                    returnCode = -1;
                    goto EXIT;
                }

                if ((*subchannel)->type != 3) continue;

                if ((*component)->packet.appType != 0xffff) {
                    if (fig0 == NULL) {
                        fig0 = (FIGtype0*)&etiFrame[index];
                        fig0->FIGtypeNumber = 0;
                        fig0->Length = 1;
                        fig0->CN = 0;
                        fig0->OE = 0;
                        fig0->PD = 1;
                        fig0->Extension = 13;
                        index += 2;
                        figSize += 2;
                    }

                    FIG0_13_longAppInfo* info =
                        (FIG0_13_longAppInfo*)&etiFrame[index];
                    info->SId = htonl((*component)->serviceId);
                    info->SCIdS = (*component)->SCIdS;
                    info->No = 1;
                    index += 5;
                    figSize += 5;
                    fig0->Length += 5;

                    FIG0_13_app* app = (FIG0_13_app*)&etiFrame[index];
                    app->setType((*component)->packet.appType);
                    app->length = 0;
                    index += 2;
                    figSize += 2;
                    fig0->Length += 2;

                    if (figSize > 30) {
                        etiLog.printHeader(TcpLog::ERR,
                                "can't add to Fic Fig 0/13, "
                                "too much packet service\n");
                        returnCode = -1;
                        goto EXIT;
                    }
                }
            }
            break;
        case 7:
            //Time and country identifier
            fig0_10 = (FIGtype0_10 *) & etiFrame[index];

            fig0_10->FIGtypeNumber = 0;
            fig0_10->Length = 5;
            fig0_10->CN = 0;
            fig0_10->OE = 0;
            fig0_10->PD = 0;
            fig0_10->Extension = 10;
            index = index + 2;

            timeData = localtime(&date);

            fig0_10->RFU = 0;
            fig0_10->setMJD(gregorian2mjd(timeData->tm_year + 1900,
                        timeData->tm_mon + 1,
                        timeData->tm_mday));
            fig0_10->LSI = 0;
            fig0_10->ConfInd = (watermarkData[watermarkPos >> 3] >>
                    (7 - (watermarkPos & 0x07))) & 1;
            if (++watermarkPos == watermarkSize) {
                watermarkPos = 0;
            }
            fig0_10->UTC = 0;
            fig0_10->setHours(timeData->tm_hour);
            fig0_10->Minutes = timeData->tm_min;
            index = index + 4;
            figSize += 6;

            fig0_9 = (FIGtype0_9*)&etiFrame[index];
            fig0_9->FIGtypeNumber = 0;
            fig0_9->Length = 4;
            fig0_9->CN = 0;
            fig0_9->OE = 0;
            fig0_9->PD = 0;
            fig0_9->Extension = 9;

            fig0_9->ext = 0;
            fig0_9->lto = 0;
            fig0_9->ensembleLto = 0;
            fig0_9->ensembleEcc = ensemble->ecc;
            fig0_9->tableId = 0x2;
            index += 5;
            figSize += 5;

            break;
        }

        memcpy(&etiFrame[index], Padding_FIB, 30 - figSize);
        index += 30 - figSize;

        CRCtmp = 0xffff;
        CRCtmp = crc16(CRCtmp, &etiFrame[(index - 30)], 30);
        CRCtmp ^= 0xffff;
        etiFrame[index++] = ((char *) &CRCtmp)[1];
        etiFrame[index++] = ((char *) &CRCtmp)[0];


        figSize = 0;
        // Insertion FIB 2
        if (alterneFIB < ensemble->services.size()) {
            service = ensemble->services.begin() + alterneFIB;

            // FIG type 1/1, SI, Service label, une instance par sous-canal
            if ((*service)->getType(ensemble) == 0) {
                fig1_1 = (FIGtype1_1 *) & etiFrame[index];

                fig1_1->FIGtypeNumber = 1;
                fig1_1->Length = 21;
                fig1_1->Charset = 0;
                fig1_1->OE = 0;
                fig1_1->Extension = 1;

                fig1_1->Sld = htons((*service)->id);
                index += 4;
                figSize += 4;
            } else {
                fig1_5 = (FIGtype1_5 *) & etiFrame[index];
                fig1_5->FIGtypeNumber = 1;
                fig1_5->Length = 23;
                fig1_5->Charset = 0;
                fig1_5->OE = 0;
                fig1_5->Extension = 5;

                fig1_5->SId = htonl((*service)->id);
                index += 6;
                figSize += 6;
            }
            memcpy(&etiFrame[index], (*service)->label.text, 16);
            index += 16;
            figSize += 16;

            etiFrame[index++] = ((char *) &(*service)->label.flag)[1];
            etiFrame[index++] = ((char *) &(*service)->label.flag)[0];
            figSize += 2;
        } else if (alterneFIB <
                ensemble->services.size() + ensemble->components.size()) {
            component = ensemble->components.begin() +
                (alterneFIB - ensemble->services.size());
            service = getService(*component, ensemble->services);
            subchannel =
                getSubchannel(ensemble->subchannels, (*component)->subchId);

            if ((*component)->label.text[0] != 0) {
                if ((*service)->getType(ensemble) == 0) {   // Programme
                    FIGtype1_4_programme *fig1_4;
                    fig1_4 = (FIGtype1_4_programme*)&etiFrame[index];

                    fig1_4->FIGtypeNumber = 1;
                    fig1_4->Length = 22;
                    fig1_4->Charset = 0;
                    fig1_4->OE = 0;
                    fig1_4->Extension = 4;
                    fig1_4->PD = 0;
                    fig1_4->rfa = 0;
                    fig1_4->SCIdS = (*component)->SCIdS;

                    fig1_4->SId = htons((*service)->id);
                    index += 5;
                    figSize += 5;
                } else {    // Data
                    FIGtype1_4_data *fig1_4;
                    fig1_4 = (FIGtype1_4_data *) & etiFrame[index];
                    fig1_4->FIGtypeNumber = 1;
                    fig1_4->Length = 24;
                    fig1_4->Charset = 0;
                    fig1_4->OE = 0;
                    fig1_4->Extension = 4;
                    fig1_4->PD = 1;
                    fig1_4->rfa = 0;
                    fig1_4->SCIdS = (*component)->SCIdS;

                    fig1_4->SId = htonl((*service)->id);
                    index += 7;
                    figSize += 7;
                }
                memcpy(&etiFrame[index], (*component)->label.text, 16);
                index += 16;
                figSize += 16;

                etiFrame[index++] = ((char *) &(*component)->label.flag)[1];
                etiFrame[index++] = ((char *) &(*component)->label.flag)[0];
                figSize += 2;
            }
        }
        memcpy(&etiFrame[index], Padding_FIB, 30 - figSize);
        index += 30 - figSize;

        CRCtmp = 0xffff;
        CRCtmp = crc16(CRCtmp, &etiFrame[(index - 30)], 30);
        CRCtmp ^= 0xffff;
        etiFrame[index++] = ((char *) &CRCtmp)[1];
        etiFrame[index++] = ((char *) &CRCtmp)[0];

        if (ensemble->mode == 3) {
            memcpy(&etiFrame[index], Padding_FIB, 30);
            index += 30;

            CRCtmp = 0xffff;
            CRCtmp = crc16(CRCtmp, &etiFrame[(index - 30)], 30);
            CRCtmp ^= 0xffff;
            etiFrame[index++] = ((char *) &CRCtmp)[1];
            etiFrame[index++] = ((char *) &CRCtmp)[0];
        }

        if (ensemble->services.size() > 30) {
            etiLog.printHeader(TcpLog::ERR,
                    "Sorry, but this software currently can't write "
                    "Service Label of more than 30 services.\n");
            returnCode = -1;
            goto EXIT;
        }

        // compteur pour FIG 0/0
        insertFIG = (insertFIG + 1) % 8;

        // compteur pour inserer FIB a toutes les 30 trames
        alterneFIB = (alterneFIB + 1) % 30;

        /**********************************************************************
         ******  Section de lecture de donnees  *******************************
         **********************************************************************/

        //Lecture des donnees dans les fichiers d'entree
        for (subchannel = ensemble->subchannels.begin();
                subchannel != ensemble->subchannels.end();
                ++subchannel) {
            int sizeSubchannel = getSizeByte(*subchannel);
            if ((*subchannel)->operations.lock != NULL) {
                (*subchannel)->operations.lock((*subchannel)->data);
            }
            result = (*subchannel)->operations.readFrame(
                    &(*subchannel)->operations,
                    (*subchannel)->data, &etiFrame[index], sizeSubchannel);
            if ((*subchannel)->operations.unlock != NULL) {
                (*subchannel)->operations.unlock((*subchannel)->data);
            }
            if (result < 0) {
                etiLog.print(TcpLog::INFO, "ETI frame number: %i\n", currentFrame);
            }
            index += sizeSubchannel;
        }


        index = (3 + fc->NST + FICL) * 4;
        for (subchannel = ensemble->subchannels.begin();
                subchannel != ensemble->subchannels.end();
                ++subchannel) {
            index += getSizeByte(*subchannel);
        }

        /******* Section EOF **************************************************/
        // End of Frame, 4 octets 
        index = (FLtmp + 1 + 1) * 4;
        eti_EOF *eof = (eti_EOF *) & etiFrame[index];

        //CRC sur le Main Stream data (MST), sur 16 bits
        index = ((fc->NST) + 2 + 1) * 4;            //position du MST
        MSTsize = ((FLtmp) - 1 - (fc->NST)) * 4;    //nb d'octets de donnees

        CRCtmp = 0xffff;
        CRCtmp = crc16(CRCtmp, &etiFrame[index], MSTsize);
        CRCtmp ^= 0xffff;
        eof->CRC = htons(CRCtmp);

        //RFU, Reserved for future use, 2 bytes, should be 0xFFFF
        eof->RFU = htons(0xFFFF);

        /******* Section TIST *************************************************/
        // TimeStamps, 24 bits + 1 octet
        index = (FLtmp + 2 + 1) * 4;
        eti_TIST *tist = (eti_TIST *) & etiFrame[index];

        if (enableTist) {
            tist->TIST = htonl(timestamp) | 0xff;
        }
        else {
            tist->TIST = htonl(0xffffff) | 0xff;
        }

        timestamp += 3 << 17;
        if (timestamp > 0xf9ffff)
        {
            timestamp -= 0xfa0000;

            // Also update MNSC time for next frame
            MNSC_increment_time = true;
        }



        /********************************************************************** 
         ***********   Section FRPD   *****************************************
         **********************************************************************/

        //Donne le nombre total d'octets utils dans la trame
        index = (FLtmp + 1 + 1 + 1 + 1) * 4;

        // Give the data to the outputs
        for (output = outputs.begin() ; output != outputs.end(); ++output) {
            if ((*output)->operations.write((*output)->data, etiFrame, index)
                    == -1) {
                etiLog.print(TcpLog::ERR, "Can't write to output %s://%s\n",
                        (*output)->outputProto, (*output)->outputName);
            }
        }

#ifdef DUMP_BRIDGE
        dumpBytes(dumpData, sizeSubChannel, stderr);
#endif // DUMP_BRIDGE

        if (currentFrame % 100 == 0) {
            if (enableTist) {
                etiLog.print(TcpLog::INFO, "ETI frame number %i Timestamp: %d + %f\n",
                        currentFrame, mnsc_time.tv_sec, 
                        (timestamp & 0xFFFFFF) / 16384000.0);
            }
            else {
                etiLog.print(TcpLog::INFO, "ETI frame number %i Time: %d, no TIST\n",
                        currentFrame, mnsc_time.tv_sec);
            }
        }
    }

EXIT:
    etiLog.print(TcpLog::DBG, "exiting...\n");
    fflush(stderr);
    //fermeture des fichiers
    for (subchannel = ensemble->subchannels.begin();
            subchannel != ensemble->subchannels.end();
            ++subchannel) {
        (*subchannel)->operations.close((*subchannel)->data);
        (*subchannel)->operations.clean(&(*subchannel)->data);
    }
    for (output = outputs.begin() ; output != outputs.end(); ++output) {
        (*output)->operations.close((*output)->data);
        (*output)->operations.clean(&(*output)->data);
    }

    for_each(ensemble->components.begin(), ensemble->components.end(), free);
    for_each(ensemble->services.begin(), ensemble->services.end(), free);
    for_each(ensemble->subchannels.begin(), ensemble->subchannels.end(), free);
    for_each(outputs.begin(), outputs.end(), free);
    ensemble->components.clear();
    ensemble->services.clear();
    ensemble->subchannels.clear();
    free(ensemble);
    outputs.clear();

    UdpSocket::clean();

    if (returnCode < 0) {
        etiLog.print(TcpLog::EMERG, "...aborting\n");
    } else {
        etiLog.print(TcpLog::DBG, "...done\n");
    }

    return returnCode;
}