File: scan.c

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

#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/poll.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <assert.h>

#include <linux/dvb/dmx.h>
#include <linux/dvb/version.h>

#include "version.h"
#include "scan.h"
#include "dump-vdr.h"
#include "dump-xine.h"
#include "dump-dvbscan.h"
#include "dump-kaffeine.h"
#include "dump-mplayer.h"
#include "dump-vlc-m3u.h"
#include "dvbscan.h"
#include "parse-dvbscan.h"
#include "countries.h"
#include "satellites.h"
#include "atsc_psip_section.h"
#include "descriptors.h"
#include "lnb.h"
#include "diseqc.h"
#include "iconv_codes.h"
#include "char-coding.h"

static char demux_devname[80];

int verbosity = 2;      // need signed -> use of fatal()

struct w_scan_flags flags = {
        0,                // readback value w_scan version {YYYYMMDD}
        SCAN_TERRESTRIAL, // scan type
        ATSC_VSB,         // default for ATSC scan
        0,                // need 2nd generation frontend
        DE,               // country index or sat index
        1,                // tuning speed {1 = fast, 2 = medium, 3 = slow}
        0,                // filter timeout {0 = default, 1 = long} 
        1,                // get_other_nits, atm always
        1,                // add_frequencies, atm always
        1,                // dump_provider, dump also provider name
        6,                // VDR version number, VDR-1.6.x
        0,                // 0 = qam auto, 1 = search qams
        1,                // scan encrypted channels = yes
        -1,               // rotor position, unused
        0x0302,           // assuming DVB API version 3.2
        0xFF,             // switch pos
        0,                // codepage, 0 = UTF-8
        0,                // print pmt
};

static unsigned int modulation_min = 0;         // initialization of modulation loop. QAM64  if FE_QAM
static unsigned int modulation_max = 1;         // initialization of modulation loop. QAM256 if FE_QAM
static unsigned int dvbc_symbolrate_min = 0;    // initialization of symbolrate loop. 6900
static unsigned int dvbc_symbolrate_max = 1;    // initialization of symbolrate loop. 6875
static unsigned int freq_offset_min = 0;        // initialization of freq offset loop. 0 == offset (0), 1 == offset(+), 2 == offset(-), 3 == offset1(+), 4 == offset2(+)
static unsigned int freq_offset_max = 4;        // initialization of freq offset loop.
static int this_channellist = DVBT_DE;          // w_scan uses by default DVB-t
static unsigned int ATSC_type = ATSC_VSB;       // 20090227: flag type vars shouldnt be signed. 
static unsigned int no_ATSC_PSIP = 0;           // 20090227: initialization was missing, signed -> unsigned                
static unsigned int serv_select = 3;            // 20080106: radio and tv as default (no service/other). 20090227: flag type vars shouldnt be signed. 
static int this_rotor_pos = -1;                 // 20090320: DVB-S/S2, current rotor position
static int committed_switch = 0;                // 20090320: DVB-S/S2, DISEQC committed switch position
static int uncommitted_switch = 0;              // 20090320: DVB-S/S2, DISEQC uncommitted switch position
static struct lnb_types_st this_lnb;            // 20090320: DVB-S/S2, LNB type, initialized in main to 'UNIVERSAL'

time_t start_time = 0;

static enum fe_spectral_inversion caps_inversion        = INVERSION_AUTO;
static enum fe_code_rate caps_fec                       = FEC_AUTO;
static enum fe_modulation caps_qam                      = QAM_AUTO;
static enum fe_modulation this_qam                      = QAM_64;
static enum fe_modulation this_atsc                     = VSB_8;
static enum fe_transmit_mode caps_transmission_mode     = TRANSMISSION_MODE_AUTO;
static enum fe_guard_interval caps_guard_interval       = GUARD_INTERVAL_AUTO;
static enum fe_hierarchy caps_hierarchy                 = HIERARCHY_AUTO;
static struct dvb_frontend_info fe_info;

enum __output_format {
        OUTPUT_VDR,
        OUTPUT_GSTREAMER,
        OUTPUT_PIDS,
        OUTPUT_XINE,
        OUTPUT_DVBSCAN_TUNING_DATA,
        OUTPUT_KAFFEINE,
        OUTPUT_MPLAYER,
        OUTPUT_VLC_M3U,
};

static enum __output_format output_format = OUTPUT_VDR;

int run_time() {
        return time(NULL) - start_time;
}

void hexdump(const char * intro, const unsigned char * buf, int len) {

        int i, j;
        char sbuf[17];

        if (verbosity < 4)
                return;

        memset(&sbuf, 0, 17);

        info("\t===================== %s ", intro);
        for (i = strlen(intro) + 1; i < 50; i++)
                info("=");
        info("\n");
        info("\tlen = %d\n", len);
        for (i = 0; i < len; i++) {
                if ((i % 16) == 0) {
                        info("%s0x%.2X: ",i?"\n\t":"\t",(i / 16) * 16);
                        }
                info("%.2X ", (uint8_t) *(buf + i));
                sbuf[i % 16] = *(buf + i);
                if (((i + 1) % 16) == 0) {
                        // remove non-printable chars
                        for (j = 0; j < 16; j++)
                                if (! ((sbuf[j] > 31)  && (sbuf[j] < 127)))
                                        sbuf[j] = ' ';
                        
                        info(": %s", sbuf);
                        memset(&sbuf, 0, 17);
                        }
                }
        if (len % 16) {
                for (i = 0; i < (len % 16); i++)
                        if (! ((sbuf[i] > 31)  && (sbuf[i] < 127)))
                                sbuf[i] = ' ';
                for (i = (len % 16); i < 16; i++)
                        info("   ");
                info(": %s", sbuf);
                }
        info("\n");
        info("\t========================================================================\n");
}


struct section_buf {
        struct list_head list;
        const char *dmx_devname;
        unsigned int run_once   : 1;
        unsigned int segmented  : 1;    /* segmented by table_id_ext */
        int fd;
        int pid;
        int table_id;
        int table_id_ext;
        int section_version_number;
        uint8_t section_done[32];
        int sectionfilter_done;
        unsigned char buf[1024];
        time_t timeout;
        time_t start_time;
        time_t running_time;
        struct section_buf *next_seg;   /* this is used to handle segmented tables (like NIT-other) */
};

static LIST_HEAD(scanned_transponders);
static LIST_HEAD(new_transponders);
static struct transponder *current_tp;

static void setup_filter (struct section_buf* s, const char *dmx_devname,
                          int pid, int table_id, int table_id_ext,
                          int run_once, int segmented);

static void add_filter (struct section_buf *s);


/* According to the DVB standards, the combination of network_id and
 * transport_stream_id should be unique, but in real life the satellite
 * operators and broadcasters don't care enough to coordinate
 * the numbering. Thus we identify TPs by frequency (scan handles only
 * one satellite at a time). Further complication: Different NITs on
 * one satellite sometimes list the same TP with slightly different
 * frequencies, so we have to search within some bandwidth.
 */
struct transponder *alloc_transponder(uint32_t frequency)
{
        struct list_head *pos, *tmp;
        struct transponder *check;
        struct transponder *tp = calloc(1, sizeof(*tp));
        int known = 0;

        tp->param.frequency = frequency;
        tp->source = 0;
        INIT_LIST_HEAD(&tp->list);
        INIT_LIST_HEAD(&tp->services);

        list_for_each_safe(pos, tmp, &new_transponders) {
                check = list_entry (pos, struct transponder, list);
                if (check->param.frequency == frequency)
                   known = 1;
                }

        if (! known)
           list_add_tail(&tp->list, &new_transponders);

        return tp;
}

static int is_nearly_same_frequency(uint32_t f1, uint32_t f2, scantype_t type)
{
        uint32_t diff;
        if (f1 == f2)
                return 1;
        diff = (f1 > f2) ? (f1 - f2) : (f2 - f1);
        //FIXME: use symbolrate etc. to estimate bandwidth
        switch(type) {
                case SCAN_SATELLITE:
                        // 2MHz
                        if (diff < 2000) {
                                debug("f1 = %u is same TP as f2 = %u (diff=%d)\n", f1, f2, diff);
                                return 1;
                                }
                        break;
                default:
                        // 750kHz
                        if (diff < 750000) {
                                debug("f1 = %u is same TP as f2 = %u (diff=%d)\n", f1, f2, diff);
                                return 1;
                                }
                }
        return 0;
}


int is_different_transponder_deep_scan(struct transponder * a, struct transponder * b, int auto_allowed) {

#define IS_DIFFERENT(A, B, _ALLOW_AUTO_, _AUTO_) ( (A != B)  && (! _ALLOW_AUTO_ || (_ALLOW_AUTO_ && (A != _AUTO_) && (B != _AUTO_)) ) )

        if (a->type != b->type)
                return 1;
        if (! is_nearly_same_frequency(a->param.frequency, b->param.frequency, a->type))
                return 1;
        switch (a->type) {
                case SCAN_TERRESTRIAL:
                        if(IS_DIFFERENT(a->param.u.terr.constellation,b->param.u.terr.constellation,auto_allowed,QAM_AUTO))
                                return 1;
                        if(IS_DIFFERENT(a->param.u.terr.bandwidth,b->param.u.terr.bandwidth,auto_allowed,8000000))
                                return 1;
                        if(IS_DIFFERENT(a->param.u.terr.code_rate_HP,b->param.u.terr.code_rate_HP,auto_allowed,FEC_AUTO))
                                return 1;
                        if(IS_DIFFERENT(a->param.u.terr.hierarchy_information,b->param.u.terr.hierarchy_information,auto_allowed,HIERARCHY_AUTO))
                                return 1;
                        if(IS_DIFFERENT(a->param.u.terr.code_rate_LP,b->param.u.terr.code_rate_LP,auto_allowed,FEC_AUTO))
                                return 1;
                        if(IS_DIFFERENT(a->param.u.terr.transmission_mode,b->param.u.terr.transmission_mode,auto_allowed,TRANSMISSION_MODE_AUTO))
                                return 1;
                        if(IS_DIFFERENT(a->param.u.terr.guard_interval,b->param.u.terr.guard_interval,auto_allowed,GUARD_INTERVAL_AUTO))
                                return 1;
                        if(IS_DIFFERENT(a->param.u.terr.delivery_system, b->param.u.terr.delivery_system, auto_allowed, SYS_DVBT))
                                return 1;
                        if(IS_DIFFERENT(a->pids.plp_id, b->pids.plp_id, auto_allowed, 0))
                                return 1;
                        if(IS_DIFFERENT(a->pids.system_id, b->pids.system_id, auto_allowed, 0))
                                return 1;
                        return 0;
                case SCAN_TERRCABLE_ATSC:
                        if(IS_DIFFERENT(a->param.u.atsc.modulation,b->param.u.atsc.modulation,auto_allowed,QAM_AUTO))
                                return 1;
                        return 0;
                case SCAN_CABLE:
                        if(IS_DIFFERENT(a->param.u.cable.modulation,b->param.u.cable.modulation,auto_allowed,QAM_AUTO))
                                return 1;
                        if(IS_DIFFERENT(a->param.u.cable.symbol_rate,b->param.u.cable.symbol_rate,0,0))
                                return 1;
                        if(IS_DIFFERENT(a->param.u.cable.fec_inner,b->param.u.cable.fec_inner,auto_allowed,FEC_AUTO))
                                return 1;
                        if(IS_DIFFERENT(a->param.u.cable.delivery_system, b->param.u.cable.delivery_system, auto_allowed, SYS_DVBC_ANNEX_AC))
                                return 1;
                        if(IS_DIFFERENT(a->pids.plp_id, b->pids.plp_id, auto_allowed, 0))
                                return 1;
                        if(IS_DIFFERENT(a->pids.system_id, b->pids.system_id, auto_allowed, 0))
                                return 1;
                        return 0;
                case SCAN_SATELLITE:
                        if(IS_DIFFERENT(a->param.u.sat.symbol_rate,b->param.u.sat.symbol_rate,0,0))
                                return 1;
                        if(IS_DIFFERENT(a->param.u.sat.modulation_system,b->param.u.sat.modulation_system,0,0))
                                return 1;
                        if(IS_DIFFERENT(a->param.u.sat.polarization,b->param.u.sat.polarization,0,0))
                                return 1;
                        if(IS_DIFFERENT(a->param.u.sat.fec_inner,b->param.u.sat.fec_inner,auto_allowed,FEC_AUTO))
                                return 1;
                        if(IS_DIFFERENT(a->param.u.sat.rolloff,b->param.u.sat.rolloff,auto_allowed,ROLLOFF_AUTO))
                                return 1;
                        if(IS_DIFFERENT(a->param.u.sat.modulation_type,b->param.u.sat.modulation_type,auto_allowed,QPSK))
                                return 1;
                        return 0;
                default:
                        fatal("unimplemented frontend type.\n");
                }
}

static struct transponder *find_transponder_by_freq(struct transponder * tn)
{
        struct list_head *pos;
        struct transponder *tp;

        /* check wether develivery system matches frontend type */        
        if (tn->type != flags.scantype)
                return NULL;
        list_for_each(pos, &scanned_transponders) {
                tp = list_entry(pos, struct transponder, list);
                if (is_nearly_same_frequency(tp->param.frequency,tn->param.frequency,tn->type))
                   return tp;
                }
        list_for_each(pos, &new_transponders) {
                tp = list_entry(pos, struct transponder, list);
                if (is_nearly_same_frequency(tp->param.frequency,tn->param.frequency,tn->type))
                   return tp;
                }
        return NULL;
}

/* identify wether tn is already in list of new transponders */
static int is_known_initial_transponder(struct transponder * tn, int auto_allowed)
{
        struct list_head *pos;
        struct transponder *tp;

        list_for_each(pos, &new_transponders) {
                tp = list_entry(pos, struct transponder, list);
                switch (tn->type) {
                        case SCAN_TERRESTRIAL:
                        case SCAN_CABLE:
                                if ((tp->type == tn->type) &&
                                    is_nearly_same_frequency(tp->param.frequency, tn->param.frequency, tp->type))
                                        return (tp->source >> 8) == 64;
                                break;
                        case SCAN_TERRCABLE_ATSC:
                                if ((tp->type == tn->type) &&
                                    is_nearly_same_frequency(tp->param.frequency, tn->param.frequency, tp->type) &&
                                   (tp->param.u.atsc.modulation == tn->param.u.atsc.modulation))
                                        return (tp->source >> 8) == 64;
                                break;
                        case SCAN_SATELLITE: 
                                if (! is_different_transponder_deep_scan(tn,tp,auto_allowed))
                                        return (tp->source >> 8) == 64;
                                break;
                        default:
                                fatal("Unhandled type %d\n", tn->type);
                        }
                }
        return 0;
}

void print_transponder(char * dest, struct transponder * t) {
        char plp_id[5];
        memset(plp_id, 0, sizeof(plp_id));
 
        switch (t->type) {
                case SCAN_TERRESTRIAL:
                        if (t->param.u.terr.delivery_system == SYS_DVBT2)
                           snprintf(&plp_id[0], sizeof(plp_id), "P%d", t->pids.plp_id);
                           
                        sprintf(dest, "%-8s f = %6d kHz I%sB%sC%sD%sT%sG%sY%s%s",
                                xine_modulation_name(t->param.u.terr.constellation),
                                t->param.frequency/1000,
                                vdr_inversion_name(t->param.inversion),
                                vdr_bandwidth_name(t->param.u.terr.bandwidth),
                                vdr_fec_name(t->param.u.terr.code_rate_HP),
                                vdr_fec_name(t->param.u.terr.code_rate_LP),
                                vdr_transmission_mode_name(t->param.u.terr.transmission_mode),
                                vdr_guard_name(t->param.u.terr.guard_interval),
                                vdr_hierarchy_name(t->param.u.terr.hierarchy_information),
                                &plp_id[0]);
                        break;
                case SCAN_TERRCABLE_ATSC:
                        sprintf(dest, "%-8s f=%d kHz",
                                atsc_mod_to_txt(t->param.u.atsc.modulation),
                                t->param.frequency/1000);
                        break;
                case SCAN_CABLE:
                        sprintf(dest, "%-8s f = %d kHz S%dC%s",
                                xine_modulation_name(t->param.u.cable.modulation),
                                t->param.frequency/1000,
                                t->param.u.cable.symbol_rate/1000,
                                vdr_fec_name(t->param.u.cable.fec_inner));
                        break;
                case SCAN_SATELLITE:
                        sprintf(dest, "%-2s f = %d kHz %s SR = %5d %4s 0,%s %5s",
                                sat_delivery_system_to_txt(t->param.u.sat.modulation_system),
                                t->param.frequency/1000,
                                sat_pol_to_txt(t->param.u.sat.polarization),
                                t->param.u.sat.symbol_rate/1000,
                                sat_fec_to_txt(t->param.u.sat.fec_inner),
                                sat_rolloff_to_txt(t->param.u.sat.rolloff),
                                sat_mod_to_txt(t->param.u.sat.modulation_type));
                
        break;
                default:
                        warning("unimplemented frontend type %d\n", t->type);
                }
}


static void copy_transponder(struct transponder *dest, struct transponder *source)
{
        struct list_head *pos;
        struct service *service;
        memcpy(&dest->pids, &source->pids, sizeof(dest->pids));
        dest->type = source->type;
        memcpy(&dest->param, &source->param, sizeof(dest->param));
        dest->source = source->source;
        dest->last_tuning_failed = source->last_tuning_failed;
        dest->other_frequency_flag = source->other_frequency_flag;
        dest->n_other_f = source->n_other_f;
        // equiv to.. http://www.mail-archive.com/linux-media@vger.kernel.org/msg14655.html 
        // Anssi Hannula <anssi.hann...@iki.fi>
        if (dest->pids.transport_stream_id != source->pids.transport_stream_id) {
                /* propagate change to any already allocated services */
                list_for_each(pos, &dest->services) {
                service = list_entry(pos, struct service, list);
                service->transport_stream_id = source->pids.transport_stream_id;
                }
        }

        if (dest->n_other_f) {
                dest->other_f = calloc(dest->n_other_f, sizeof(uint32_t));
                memcpy(dest->other_f, source->other_f, dest->n_other_f * sizeof(uint32_t));
        } 

        else
                dest->other_f = NULL;
        if (source->network_name != NULL) {
                if (dest->network_name != NULL)
                        free(dest->network_name);
                dest->network_name = (char *) malloc(strlen(source->network_name));
                memcpy(dest->network_name, source->network_name, strlen(source->network_name));
                dest->network_name[strlen(source->network_name)] = '\0';
                }
        else
                dest->network_name = NULL;
        if (source->network_change.num_networks > 0) {
           int i;
           dest->network_change.num_networks = source->network_change.num_networks;
           dest->network_change.network = calloc(source->network_change.num_networks, sizeof(changed_network_t));
           for (i = 0; i < source->network_change.num_networks; i++) {
               dest->network_change.network[i] = source->network_change.network[i];
               dest->network_change.network[i].loop = 
                     calloc(source->network_change.network[i].num_changes,sizeof(network_change_loop_t));
               memcpy(&dest->network_change.network[i].loop, &source->network_change.network[i].loop,
                      source->network_change.network[i].num_changes * sizeof(network_change_loop_t));
               }
           }
        else
           dest->network_change.num_networks = 0;
}

/* service_ids are guaranteed to be unique within one TP
 * (the DVB standards say theay should be unique within one
 * network, but in real life...)
 */
static struct service *alloc_service(struct transponder *tp, int service_id)
{
        struct service *s = calloc(1, sizeof(*s));
        INIT_LIST_HEAD(&s->list);
        s->service_id = service_id;
        list_add_tail(&s->list, &tp->services);
        return s;
}

static struct service *find_service(struct transponder *tp, int service_id)
{
        struct list_head *pos;
        struct service *s;

        list_for_each(pos, &tp->services) {
                s = list_entry(pos, struct service, list);
                if (s->service_id == service_id)
                        return s;
        }
        return NULL;
}

static int find_descriptor(uint8_t tag, const unsigned char *buf,
                int descriptors_loop_len,
                const unsigned char **desc, int *desc_len)
{
        while (descriptors_loop_len > 0) {
                unsigned char descriptor_tag = buf[0];
                unsigned char descriptor_len = buf[1] + 2;

                if (!descriptor_len) {
                        warning("descriptor_tag == 0x%02x, len is 0\n", descriptor_tag);
                        break;
                }

                if (tag == descriptor_tag) {
                        if (desc)
                                *desc = buf;
                        if (desc_len)
                                *desc_len = descriptor_len;
                        return 1;
                }

                buf += descriptor_len;
                descriptors_loop_len -= descriptor_len;
        }
        return 0;
}

static void parse_descriptors(enum table_id t, const unsigned char *buf,
                              int descriptors_loop_len, void *data, scantype_t scantype) {
        while (descriptors_loop_len > 0) {
                unsigned char descriptor_tag = buf[0];
                unsigned char descriptor_len = buf[1] + 2;

                if (!descriptor_len) {
                        debug("descriptor_tag == 0x%02x, len is 0\n", descriptor_tag);
                        break;
                }

                switch (descriptor_tag) {
                        case MHP_application_descriptor:
                        case MHP_application_name_desriptor:
                        case MHP_transport_protocol_descriptor:
                        case dvb_j_application_descriptor:
                        case dvb_j_application_location_descriptor:
                                break;
                        case ca_descriptor: /* 20080106 */
                                if (t == TABLE_PMT)
                                        parse_ca_descriptor (buf, data);        
                                break;        
                        case iso_639_language_descriptor:
                                if (t == TABLE_PMT)
                                        parse_iso639_language_descriptor (buf, data);
                                break;
                        case application_icons_descriptor:
                        case carousel_identifier_descriptor:
                                break;
                        case network_name_descriptor:
                                if (t == TABLE_NIT_ACT)
                                        parse_network_name_descriptor (buf, data);
                                break;
                        case service_list_descriptor:
                        case stuffing_descriptor:
                                break;
                        case satellite_delivery_system_descriptor:
                                if ((scantype == SCAN_SATELLITE) && ((t == TABLE_NIT_ACT) || (t == TABLE_NIT_OTH)))
                                        parse_satellite_delivery_system_descriptor (buf, data, caps_inversion);
                                break;
                        case cable_delivery_system_descriptor:
                                if ((scantype == SCAN_CABLE) && ((t == TABLE_NIT_ACT) || (t == TABLE_NIT_OTH)))
                                        parse_cable_delivery_system_descriptor (buf, data, caps_inversion);
                                break;
                        case vbi_data_descriptor:
                        case vbi_teletext_descriptor:
                        case bouquet_name_descriptor:
                                break;
                        case service_descriptor:
                                if ((t == TABLE_SDT_ACT) || (t == TABLE_SDT_OTH))
                                        parse_service_descriptor (buf, data, flags.codepage);
                                break;
                        case country_availability_descriptor:
                        case linkage_descriptor:
                        case nvod_reference_descriptor:
                        case time_shifted_service_descriptor:
                        case short_event_descriptor:
                        case extended_event_descriptor:
                        case time_shifted_event_descriptor:
                        case component_descriptor:
                        case mosaic_descriptor: 
                        case stream_identifier_descriptor:
                                break;
                        case ca_identifier_descriptor:
                                if ((t == TABLE_SDT_ACT) || (t == TABLE_SDT_OTH))
                                        parse_ca_identifier_descriptor (buf, data);
                                break;
                        case content_descriptor:
                        case parental_rating_descriptor:
                        case teletext_descriptor:
                        case telephone_descriptor:
                        case local_time_offset_descriptor:
                        case subtitling_descriptor:
                                parse_subtitling_descriptor (buf, data);
                                break;
                        case terrestrial_delivery_system_descriptor:
                                if ((scantype == SCAN_TERRESTRIAL) && ((t == TABLE_NIT_ACT) || (t == TABLE_NIT_OTH)))
                                        parse_terrestrial_delivery_system_descriptor (buf, data, caps_inversion);
                                break;
                        case extension_descriptor: // 6.2.16 Extension descriptor
                                switch (buf[2]) { // descriptor_tag_extension;
                                     // see descriptors.h: _extended_descriptors && 300468v011101p 6.4
                                     case C2_delivery_system_descriptor:
                                          if ((scantype == SCAN_CABLE) && ((t == TABLE_NIT_ACT) || (t == TABLE_NIT_OTH)) &&
                                              (fe_info.caps & FE_CAN_2G_MODULATION)) {
                                             parse_C2_delivery_system_descriptor (buf, data, caps_inversion);
                                             }
                                     case T2_delivery_system_descriptor:
                                          if ((scantype == SCAN_TERRESTRIAL) && ((t == TABLE_NIT_ACT) || (t == TABLE_NIT_OTH)) &&
                                              (fe_info.caps & FE_CAN_2G_MODULATION)) {
                                             parse_T2_delivery_system_descriptor (buf, data, caps_inversion);
                                             }
                                          break;
                                     case SH_delivery_system_descriptor:
                                          if (((scantype == SCAN_SATELLITE) || (scantype == SCAN_TERRESTRIAL)) &&
                                              ((t == TABLE_NIT_ACT) || (t == TABLE_NIT_OTH))) {
                                             parse_SH_delivery_system_descriptor (buf, data, caps_inversion);
                                             }
                                          break;
                                     case network_change_notify_descriptor:
                                          parse_network_change_notify_descriptor(buf, &((struct transponder *) data)->network_change);
                                          break;
                                     // all other extended descriptors here: do nothing so far.
                                     case image_icon_descriptor:
                                     case cpcm_delivery_signalling_descriptor:
                                     case CP_descriptor:
                                     case CP_identifier_descriptor:
                                     case supplementary_audio_descriptor:
                                     case message_descriptor:
                                     case target_region_descriptor:
                                     case target_region_name_descriptor:
                                     case service_relocated_descriptor:
                                     case XAIT_PID_descriptor_descriptor:
                                     case video_depth_range_descriptor :
                                     case T2MI_descriptor:
                                     default:;
                                     }
                                break;
                        case multilingual_network_name_descriptor:
                        case multilingual_bouquet_name_descriptor:
                        case multilingual_service_name_descriptor:
                        case multilingual_component_descriptor:
                        case private_data_specifier_descriptor:
                        case service_move_descriptor:
                        case short_smoothing_buffer_descriptor:
                                break;
                        case frequency_list_descriptor:
                                if ((scantype == SCAN_TERRESTRIAL) && ((t == TABLE_NIT_ACT) || (t == TABLE_NIT_OTH)))
                                        parse_frequency_list_descriptor (buf, data);
                                break;
                        case partial_transport_stream_descriptor:
                        case data_broadcast_descriptor:
                        case scrambling_descriptor:
                        case data_broadcast_id_descriptor:
                        case transport_stream_descriptor:
                        case dsng_descriptor:
                        case pdc_descriptor:
                        case ac3_descriptor:
                        case ancillary_data_descriptor:
                        case cell_list_descriptor:
                        case cell_frequency_link_descriptor:
                        case announcement_support_descriptor:
                        case application_signalling_descriptor:
                        case service_identifier_descriptor:
                        case service_availability_descriptor:
                        case default_authority_descriptor:
                        case related_content_descriptor:
                        case tva_id_descriptor:
                        case content_identifier_descriptor:
                        case time_slice_fec_identifier_descriptor:
                        case ecm_repetition_rate_descriptor:
                                break;
                        case s2_satellite_delivery_system_descriptor:
                                if ((scantype == SCAN_SATELLITE) && ((t == TABLE_NIT_ACT) || (t == TABLE_NIT_OTH)) &&
                                    (fe_info.caps & FE_CAN_2G_MODULATION))
                                        parse_S2_satellite_delivery_system_descriptor(buf, data);
                                break;
                        case enhanced_ac3_descriptor:
                        case dts_descriptor:
                        case aac_descriptor:
                                break;                
                        case 0x83:
                        case 0xF2: // 0xF2 Private DVB Descriptor  Premiere.de, Content Transmission Descriptor
                                break;                     
                        default:
                                verbosedebug("skip descriptor 0x%02x\n", descriptor_tag);
                        }

                buf += descriptor_len;
                descriptors_loop_len -= descriptor_len;
        }
}


static void parse_pat(const unsigned char *buf, int section_length,
                      int transport_stream_id)
{
        hexdump(__FUNCTION__, buf, section_length);
        while (section_length > 0) {
                struct service *s;
                int service_id = (buf[0] << 8) | buf[1];

                if (service_id == 0) {
                        verbosedebug ("skipping %02x %02x %02x %02x (service_id == 0)\n", buf[0],buf[1],buf[2],buf[3]);
                        buf += 4;               /*  skip nit pid entry... */
                        section_length -= 4;
                        continue;
                }
                /* SDT might have been parsed first... */
                s = find_service(current_tp, service_id);
                if (!s)
                        s = alloc_service(current_tp, service_id);
                s->pmt_pid = ((buf[2] & 0x1f) << 8) | buf[3];
                if (!s->priv && s->pmt_pid) {
                        s->priv = malloc(sizeof(struct section_buf));
                        setup_filter(s->priv, demux_devname,
                                     s->pmt_pid, TABLE_PMT, -1, 1, 0);

                        add_filter (s->priv);
                }

                buf += 4;
                section_length -= 4;
        }
}


static void parse_pmt (const unsigned char *buf, int section_length, int service_id)
{
        int program_info_len;
        struct service *s;
        char msg_buf[14 * AUDIO_CHAN_MAX + 1];
        char *tmp;
        int i;
        hexdump(__FUNCTION__, buf, section_length);
        s = find_service (current_tp, service_id);
        if (!s) {
                error("PMT for service_id 0x%04x was not in PAT\n", service_id);
                return;
        }

        s->pcr_pid = ((buf[0] & 0x1f) << 8) | buf[1];
        program_info_len = ((buf[2] & 0x0f) << 8) | buf[3];

        // 20080106, search PMT program info for CA Ids
        buf +=4;
        section_length -= 4;

        while (program_info_len > 0) {
                int descriptor_length = ((int)buf[1]) + 2;
                parse_descriptors(TABLE_PMT, buf, section_length, s, flags.scantype);
                buf += descriptor_length;
                section_length   -= descriptor_length;
                program_info_len -= descriptor_length;
                }

        while (section_length > 0) {
                int ES_info_len = ((buf[3] & 0x0f) << 8) | buf[4];
                int elementary_pid = ((buf[1] & 0x1f) << 8) | buf[2];

                switch (buf[0]) { // stream type
                case iso_iec_11172_video_stream:
                case iso_iec_13818_1_11172_2_video_stream:
                        moreverbose("  VIDEO     : PID %d (stream type 0x%X)\n", elementary_pid, buf[0]);
                        if (s->video_pid == 0) {
                                s->video_pid = elementary_pid;
                                s->video_stream_type = buf[0];
                                }
                        break;
                case iso_iec_11172_audio_stream:
                case iso_iec_13818_3_audio_stream:
                        moreverbose("  AUDIO     : PID %d (stream type 0x%X)\n", elementary_pid, buf[0]);
                        if (s->audio_num < AUDIO_CHAN_MAX) {
                                s->audio_pid[s->audio_num] = elementary_pid;
                                s->audio_stream_type[s->audio_num] = buf[0];
                                s->audio_num++;
                                parse_descriptors (TABLE_PMT, buf + 5, ES_info_len, s, flags.scantype);
                        }
                        else
                                warning("more than %i audio channels, truncating\n", AUDIO_CHAN_MAX);
                        break;
                case iso_iec_13818_1_private_sections:
                case iso_iec_13818_1_private_data:
                   /* ITU-T Rec. H.222.0 | ISO/IEC 13818-1 PES packets containing private data*/

                        if (find_descriptor(teletext_descriptor, buf + 5, ES_info_len, NULL, NULL)) {
                                moreverbose("  TELETEXT  : PID %d\n", elementary_pid);
                                s->teletext_pid = elementary_pid;
                                break;
                        }
                        else if (find_descriptor(subtitling_descriptor, buf + 5, ES_info_len, NULL, NULL)) {
                                /* Note: The subtitling descriptor can also signal
                                 * teletext subtitling, but then the teletext descriptor
                                 * will also be present; so we can be quite confident
                                 * that we catch DVB subtitling streams only here, w/o
                                 * parsing the descriptor. */
                                moreverbose("  SUBTITLING: PID %d\n", elementary_pid);
                                s->subtitling_pid[s->subtitling_num++] = elementary_pid;
                                break;
                        }
                        else if (find_descriptor(ac3_descriptor, buf + 5, ES_info_len, NULL, NULL)) {
                                moreverbose("  AC3       : PID %d (stream type 0x%X)\n", elementary_pid, buf[0]);
                                if (s->ac3_num < AC3_CHAN_MAX) {
                                        s->ac3_pid[s->ac3_num] = elementary_pid;
                                        s->ac3_stream_type[s->ac3_num] = buf[0];
                                        s->ac3_num++;
                                        parse_descriptors (TABLE_PMT, buf + 5, ES_info_len, s, flags.scantype);
                                }
                                else
                                        warning("more than %i ac3 audio channels, truncating\n",
                                             AC3_CHAN_MAX);
                                break;
                        }
                        else if (find_descriptor(enhanced_ac3_descriptor, buf + 5, ES_info_len, NULL, NULL)) {
                                moreverbose("  EAC3      : PID %d (stream type 0x%X)\n", elementary_pid, buf[0]);
                                if (s->ac3_num < AC3_CHAN_MAX) {
                                        s->ac3_pid[s->ac3_num] = elementary_pid;
                                        s->ac3_stream_type[s->ac3_num] = buf[0];
                                        s->ac3_num++;
                                        parse_descriptors (TABLE_PMT, buf + 5, ES_info_len, s, flags.scantype);
                                }
                                else
                                        warning("more than %i eac3 audio channels, truncating\n",
                                             AC3_CHAN_MAX);
                                break;
                        }
                        /* we shouldn't reach this one, usually it should be Teletext, Subtitling or AC3 .. */
                        moreverbose("  unknown private data: PID 0x%04x\n", elementary_pid);
                        break;
                case iso_iec_13522_MHEG:
                        /*
                        MHEG-5, or ISO/IEC 13522-5, is part of a set of international standards relating to the
                        presentation of multimedia information, standardized by the Multimedia and Hypermedia Experts Group (MHEG).
                        It is most commonly used as a language to describe interactive television services. */
                        moreverbose("  MHEG      : PID %d\n", elementary_pid);
                        break;
                case iso_iec_13818_1_Annex_A_DSM_CC:
                        moreverbose("  DSM CC    : PID %d\n", elementary_pid);
                        break;
                case iso_iec_13818_1_11172_1_auxiliary:
                        moreverbose("  ITU-T Rec. H.222.0 | ISO/IEC 13818-1/11172-1 auxiliary : PID %d\n", elementary_pid);
                        break;
                case iso_iec_13818_6_type_a_multiproto_encaps:
                        moreverbose("  ISO/IEC 13818-6 Multiprotocol encapsulation    : PID %d\n", elementary_pid);
                        break;
                case iso_iec_13818_6_type_b:
                        /*
                        Digital storage media command and control (DSM-CC) is a toolkit for control channels associated
                        with MPEG-1 and MPEG-2 streams. It is defined in part 6 of the MPEG-2 standard (Extensions for DSM-CC).
                        DSM-CC may be used for controlling the video reception, providing features normally found
                        on VCR (fast-forward, rewind, pause, etc). It may also be used for a wide variety of other purposes
                        including packet data transport. MPEG-2 ISO/IEC 13818-6 (part 6 of the MPEG-2 standard).

                        DSM-CC defines or extends five distinct protocols:
                        * User-User 
                        * User-Network 
                        * MPEG transport profiles (profiles to the standard MPEG transport protocol ISO/IEC 13818-1 to allow
                                transmission of event, synchronization, download, and other information in the MPEG transport stream)
                        * Download 
                        * Switched Digital Broadcast-Channel Change Protocol (SDB/CCP)
                                Enables a client to remotely switch from channel to channel in a broadcast environment.
                                Used to attach a client to a continuous-feed session (CFS) or other broadcast feed. Sometimes used in pay-per-view.
                        */
                        moreverbose("  DSM-CC U-N Messages : PID %d\n", elementary_pid);
                        break;
                case iso_iec_13818_6_type_c://DSM-CC Stream Descriptors
                        moreverbose("  ISO/IEC 13818-6 Stream Descriptors : PID %d\n", elementary_pid);
                        break;
                case iso_iec_13818_6_type_d://DSM-CC Sections (any type, including private data)
                        moreverbose("  ISO/IEC 13818-6 Sections (any type, including private data) : PID %d\n", elementary_pid);
                        break;
                case iso_iec_13818_1_auxiliary:
                        moreverbose("  ISO/IEC 13818-1 auxiliary : PID %d\n", elementary_pid);
                        break;
                case iso_iec_13818_7_audio_w_ADTS_transp:
                        moreverbose("  ADTS Audio Stream (usually AAC) : PID %d (stream type 0x%X)\n", elementary_pid, buf[0]);
                        if ((output_format == OUTPUT_VDR) && (flags.vdr_version < 7))
                           break; /* not supported by VDR-1.2..1.7.?? */
                        if (s->audio_num < AUDIO_CHAN_MAX) {
                                s->audio_pid[s->audio_num] = elementary_pid;
                                s->audio_stream_type[s->audio_num] = buf[0];
                                s->audio_num++;
                                parse_descriptors (TABLE_PMT, buf + 5, ES_info_len, s, flags.scantype);
                        }
                        else
                                warning("more than %i audio channels, truncating\n", AUDIO_CHAN_MAX);
                        break;
                case iso_iec_14496_2_visual:
                        moreverbose("  ISO/IEC 14496-2 Visual : PID %d\n", elementary_pid);
                        break;
                case iso_iec_14496_3_audio_w_LATM_transp:
                        moreverbose("  ISO/IEC 14496-3 Audio with LATM transport syntax as def. in ISO/IEC 14496-3/AMD1 : PID %d (stream type 0x%X)\n", elementary_pid, buf[0]);
                        if ((output_format == OUTPUT_VDR) && (flags.vdr_version < 7))
                           break; /* not supported by VDR-1.2..1.7.?? */
                        if (s->audio_num < AUDIO_CHAN_MAX) {
                                s->audio_pid[s->audio_num] = elementary_pid;
                                s->audio_stream_type[s->audio_num] = buf[0];
                                s->audio_num++;
                                parse_descriptors (TABLE_PMT, buf + 5, ES_info_len, s, flags.scantype);
                        }
                        else
                                warning("more than %i audio channels, truncating\n", AUDIO_CHAN_MAX);
                        break;
                case iso_iec_14496_1_packet_stream_in_PES:
                        moreverbose("  ISO/IEC 14496-1 SL-packetized stream or FlexMux stream carried in PES packets : PID 0x%04x\n", elementary_pid);
                        break;
                case iso_iec_14496_1_packet_stream_in_14996:
                        moreverbose("  ISO/IEC 14496-1 SL-packetized stream or FlexMux stream carried in ISO/IEC 14496 sections : PID 0x%04x\n", elementary_pid);
                        break;
                case iso_iec_13818_6_synced_download_protocol:
                        moreverbose("  ISO/IEC 13818-6 DSM-CC synchronized download protocol : PID 0x%04x\n", elementary_pid);
                        break;
                case metadata_in_PES:
                        moreverbose("  Metadata carried in PES packets using the Metadata Access Unit Wrapper : PID 0x%04x\n", elementary_pid);
                        break;
                case metadata_in_metadata_sections:
                        moreverbose("  Metadata carried in metadata_sections : PID 0x%04x\n", elementary_pid);
                        break;
                case metadata_in_iso_iec_13818_6_data_carous:
                        moreverbose("  Metadata carried in ISO/IEC 13818-6 (DSM-CC) Data Carousel : PID 0x%04x\n", elementary_pid);
                        break;
                case metadata_in_iso_iec_13818_6_obj_carous:
                        moreverbose("  Metadata carried in ISO/IEC 13818-6 (DSM-CC) Object Carousel : PID 0x%04x\n", elementary_pid);
                        break;
                case metadata_in_iso_iec_13818_6_synced_dl:
                        moreverbose("  Metadata carried in ISO/IEC 13818-6 Synchronized Download Protocol using the Metadata Access Unit Wrapper : PID 0x%04x\n", elementary_pid);
                        break;
                case iso_iec_13818_11_IPMP_stream:
                        moreverbose("  IPMP stream (defined in ISO/IEC 13818-11, MPEG-2 IPMP) : PID 0x%04x\n", elementary_pid);
                        break;
                case iso_iec_14496_10_AVC_video_stream:
                        moreverbose("  AVC Video stream, ITU-T Rec. H.264 | ISO/IEC 14496-10 : PID %d (stream type 0x%X)\n", elementary_pid, buf[0]);
                        if (s->video_pid == 0) {
                                s->video_pid = elementary_pid;
                                s->video_stream_type = buf[0];
                                }
                        break;
                case atsc_a_52b_ac3:
                        moreverbose("  AC-3 Audio per ATSC A/52B : PID %d (stream type 0x%X)\n", elementary_pid, buf[0]);
                        if ((output_format == OUTPUT_VDR) && (flags.vdr_version < 7))
                           break; /* not supported by VDR-1.2..1.7.13 */
                        if (s->ac3_num < AC3_CHAN_MAX) {
                                s->ac3_pid[s->ac3_num] = elementary_pid;
                                s->ac3_stream_type[s->ac3_num] = buf[0];
                                s->ac3_num++;
                                parse_descriptors (TABLE_PMT, buf + 5, ES_info_len, s, flags.scantype);
                        }
                        else
                                warning("more than %i ac3 audio channels, truncating\n", AC3_CHAN_MAX);
                        break;
                default:
                        moreverbose("  OTHER     : PID %d TYPE 0x%02x\n", elementary_pid, buf[0]);
                }

                buf += ES_info_len + 5;
                section_length -= ES_info_len + 5;
        }


        tmp = msg_buf;
        tmp += sprintf(tmp, "%d (%.4s)", s->audio_pid[0], s->audio_lang[0]);

        if (s->audio_num >= AUDIO_CHAN_MAX) {
                warning("more than %i audio channels: %i, truncating to %i\n",
                      AUDIO_CHAN_MAX-1, s->audio_num, AUDIO_CHAN_MAX);
                s->audio_num = AUDIO_CHAN_MAX;
        }

        for (i=1; i<s->audio_num; i++)
                tmp += sprintf(tmp, ", %d (%.4s)", s->audio_pid[i], s->audio_lang[i]);

        debug("0x%04x 0x%04x: %s -- %s, pmt_pid 0x%04x, vpid 0x%04x, apid %s\n",
            s->transport_stream_id,
            s->service_id,
            s->provider_name, s->service_name,
            s->pmt_pid, s->video_pid, msg_buf);
}


static void parse_nit (const unsigned char *buf, int section_length, int table_id, int network_id)
{
        char buffer[60];
        int descriptors_loop_len = ((buf[0] & 0x0f) << 8) | buf[1];

        hexdump(__FUNCTION__, buf, section_length);

        if (section_length < descriptors_loop_len + 4)
        {
                warning("section too short: network_id == 0x%04x, section_length == %i, "
                     "descriptors_loop_len == %i\n",
                     network_id, section_length, descriptors_loop_len);
                return;
        }
        // update network_name
        parse_descriptors (table_id, buf + 2, descriptors_loop_len, current_tp, flags.scantype);
        section_length -= descriptors_loop_len + 4;
        buf += descriptors_loop_len + 4;

        while (section_length > 6) {
                int transport_stream_id = (buf[0] << 8) | buf[1];
                struct transponder *t = NULL, tn;

                descriptors_loop_len = ((buf[4] & 0x0f) << 8) | buf[5];

                if (section_length < descriptors_loop_len + 4)
                {
                        warning("section too short: transport_stream_id == 0x%04x, "
                             "section_length == %i, descriptors_loop_len == %i\n",
                             transport_stream_id, section_length,
                             descriptors_loop_len);
                        break;
                }

                debug("transport_stream_id 0x%04x\n", transport_stream_id);

                memset(&tn, 0, sizeof(tn));
                tn.type = -1;
                tn.pids.network_id = network_id;
                tn.pids.original_network_id = (buf[2] << 8) | buf[3];   /* onid patch by Hartmut Birr */
                tn.pids.transport_stream_id = transport_stream_id;
                tn.network_name = NULL;

                if ((flags.scantype == SCAN_TERRESTRIAL) && (table_id == TABLE_NIT_ACT)) {
                   /* the T2_delivery_system doesnt cover the complete parameter set and center frequency
                    * may be missing at all. So copy the current parameters including freq and let the
                    * hardware deal with it. The standard terrestrial_delivery_descriptor will overwrite them anyway.
                    *
                    * All other properties of an DVB-T2 signal are transmitted in the L1 signalling
                    * (L1-pre signalling && L1-post signalling) according to en-302755 7.2.
                    * L1 signalling data are not transmitted in the NIT data, bit in the T2 Frame,
                    * see ETSI TR 102 831, chapter 8.10 Layer-1 signalling:
                    * - CELL_ID, NETWORK_ID, T2_SYSTEM_ID
                    * - FREQUENCY (if known, 0 otherwise; may be several)
                    * - per PLP:
                    *         * frequency index
                    *         * PLP_GROUP_ID
                    *         * coderate
                    *         * modulation
                    *         * I/Q rotation
                    *         * FEC type 16k/64k ...
                    */
                   tn.param = current_tp->param;
                   }

                parse_descriptors (table_id, buf + 6, descriptors_loop_len, &tn, flags.scantype);
                tn.source |= table_id << 8;                
                
                if ((t = find_transponder_by_freq(&tn)) != NULL) {
                        /* this transponder is already known.
                         * should we update its informations?
                         */
                        if (table_id == TABLE_NIT_ACT) {
                                /* only nit_actual should update transponders,
                                 * too much garbage in satellite nit_other.
                                 */
                                if (is_different_transponder_deep_scan(t, &tn, 0) || 
                                    t->source != tn.source) {
                                        /* some of the informations is still set to AUTO */
                                        print_transponder(buffer, t);
                                        info("\tupdating transponder:\n\t   (%s) 0x%.4X\n", buffer, t->source);
                                        if (t->network_name != NULL) {
                                                // copy_transponder would overwrite network_name.
                                                tn.network_name = (char *) malloc(strlen(t->network_name));
                                                memcpy(tn.network_name, t->network_name, strlen(t->network_name));
                                                tn.network_name[strlen(t->network_name)] = '\0';
                                                }
                                        else
                                                tn.network_name = NULL;
                                        copy_transponder(t, &tn);
                                        print_transponder(buffer, t);
                                        info("\tto (%s) 0x%.4X\n", buffer, t->source);
                                        }
                                }
                        }
                else {
                        /* we could not find the transponder by freq and fe_type.
                         * probably a new one - so adding it to scan list
                         */
                        if (flags.add_frequencies > 0 && (tn.type == flags.scantype)) {
                                t = alloc_transponder(tn.param.frequency);
                                copy_transponder(t, &tn);
                                /* some transponders need explicitly pilot *off* or *on* ,
                                   but NIT doesn't reflect this flag. Setting to 'auto' in
                                   the hope, that the dvb hardware and/or driver will handle
                                   it correctly.
                                 */
                                if (t->type == SCAN_SATELLITE)
                                        t->param.u.sat.pilot = PILOT_AUTO;
                                print_transponder(buffer, t);
                                info("\tnew transponder:\n\t   (%s) 0x%.4X\n", buffer, t->source);
                                }
                        }
                section_length -= descriptors_loop_len + 6;
                buf += descriptors_loop_len + 6;
        }
}


static void parse_sdt (const unsigned char *buf, int section_length,
                int transport_stream_id)
{
        hexdump(__FUNCTION__, buf, section_length);

        buf += 3;              /*  skip original network id + reserved field */

        while (section_length > 4) {
                int service_id = (buf[0] << 8) | buf[1];
                int descriptors_loop_len = ((buf[3] & 0x0f) << 8) | buf[4];
                struct service *s;

                if (section_length < descriptors_loop_len || !descriptors_loop_len)
                {
                        warning("section too short: service_id == 0x%02x, section_length == %i, "
                             "descriptors_loop_len == %i\n",
                             service_id, section_length,
                             descriptors_loop_len);
                        break;
                }

                s = find_service(current_tp, service_id);
                if (!s)
                        /* maybe PAT has not yet been parsed... */
                        s = alloc_service(current_tp, service_id);

                s->running = (buf[3] >> 5) & 0x7;
                s->scrambled = (buf[3] >> 4) & 1;

                parse_descriptors (TABLE_SDT_ACT, buf + 5, descriptors_loop_len, s, flags.scantype);

                section_length -= descriptors_loop_len + 5;
                buf += descriptors_loop_len + 5;
        }
}

static void parse_psip_descriptors(struct service *s, const unsigned char *buf, int len)
{
        unsigned char *b = (unsigned char *) buf;
        int descriptor_length;

        hexdump(__FUNCTION__, buf, len);

        while (len > 0) {
                descriptor_length = b[1];
                switch (b[0]) {
                        case atsc_service_location_descriptor:
                                parse_atsc_service_location_descriptor(s, b);
                                break;
                        case atsc_extended_channel_name_descriptor:
                                parse_atsc_extended_channel_name_descriptor(s, b);
                                break;
                        default:
                                warning("unhandled psip descriptor: %02x\n",b[0]);
                                break;
                }
                b += 2 + descriptor_length;
                len -= 2 + descriptor_length;
        }
}

static void parse_psip_vct (const unsigned char *buf, int section_length,
                int table_id, int transport_stream_id)
{
        (void)section_length;
        (void)table_id;
        (void)transport_stream_id;
        int num_channels_in_section = buf[1];
        int i;
        int pseudo_id = 0xffff;
        unsigned char *b = (unsigned char *) buf + 2;

        hexdump(__FUNCTION__, buf, section_length);

        for (i = 0; i < num_channels_in_section; i++) {
                struct service *s;
                struct tvct_channel ch = read_tvct_channel(b);

                switch (ch.service_type) {
                        case atsc_analog_television:
                        case atsc_digital_television:   /* ATSC TV */
                        case atsc_radio:                /* ATSC Radio */
                                break;
                        case atsc_data:                 /* ATSC Data */
                        default:
                                continue;
                }

                if (ch.program_number == 0)
                        ch.program_number = --pseudo_id;

                /* 0x40 << 8 | {0xC8,0xC9} is not 100% correct here,
                 * but for w_scans purpose its easier to handle. ;-)
                 * generally speaking it should be {0xC800,0xC900}.
                 *
                 * ch.carrier_frequency defaults to '0' && non-zero is deprecated,
                 * so dont try to find the transponder by freq, stamp current_transponder only.
                 * May be finding transponder by transport_stream_id from PAT. However, setting
                 * t->pids.transport_stream_id from data in PAT may collide with the current DVB scan algorithm.
                 */
                current_tp->source = 0x40 << 8 | table_id; 
                s = find_service(current_tp, ch.program_number);
                if (!s)
                        s = alloc_service(current_tp, ch.program_number);

                if (s->service_name)
                        free(s->service_name);
                /* TODO: according to a_65-2009.pdf TABLE 6.4 short_name is 7*16 uimsbf, to be interpreted as UTF16;
                 *       the patch by mk that added atsc needs to be reviewed and compared to atsc specs a63, a65b, a69.
                 *       And as i'm using iconv() anyway, UTF16->users_charset conversation can be added - but carefully,
                 *       mistakes may easily break atsc scan at all.
                 *         --wirbel 20120414
                 */
                s->service_name = calloc(8,sizeof(unsigned char));
                /* TODO find a better solution to convert UTF-16 */
                s->service_name[0] = ch.short_name0;
                s->service_name[1] = ch.short_name1;
                s->service_name[2] = ch.short_name2;
                s->service_name[3] = ch.short_name3;
                s->service_name[4] = ch.short_name4;
                s->service_name[5] = ch.short_name5;
                s->service_name[6] = ch.short_name6;
                s->service_name[7] = '\0';

                parse_psip_descriptors(s,&b[32],ch.descriptors_length);

                s->channel_num = ch.major_channel_number << 10 | ch.minor_channel_number;

                if (ch.hidden) {
                        s->running = rm_not_running;
                        info("service is not running, pseudo program_number.");
                } else {
                        s->running = rm_running;
                        info("service is running.");
                }

                info(" Channel number: %d:%d. Name: '%s'\n",
                        ch.major_channel_number, ch.minor_channel_number,s->service_name);

                b += 32 + ch.descriptors_length;
        }
}

static int get_bit (uint8_t *bitfield, int bit)
{
        return (bitfield[bit/8] >> (bit % 8)) & 1;
}

static void set_bit (uint8_t *bitfield, int bit)
{
        bitfield[bit/8] |= 1 << (bit % 8);
}


/**
 *   returns 0 when more sections are expected
 *           1 when all sections are read on this pid
 *          -1 on invalid table id
 */
static int parse_section (struct section_buf *s)
{
        const unsigned char *buf = s->buf;
        int table_id;
      //int section_syntax_indicator;
        int section_length;
        int table_id_ext;
        int section_version_number;
      //int current_next_indicator;
        int section_number;
        int last_section_number;
      //int pcr_pid;
      //int program_info_length;
        int i;

        table_id = buf[0];
        if (s->table_id != table_id)
                return -1;
      //section_syntax_indicator = buf[1] & 0x80;
        section_length = (((buf[1] & 0x0f) << 8) | buf[2]) - 11;

        if (! crc_check(&buf[0],section_length+14)) {
           int verbosity = 5;
           hexdump(__FUNCTION__,&buf[0], section_length+14);
           if (s->timeout < 5 * repetition_rate(flags.scantype, s->table_id)) {
              info("increasing filter timeout.\n");
              s->timeout = 5 * repetition_rate(flags.scantype, s->table_id);
              }
           return 0;
           }

        table_id_ext = (buf[3] << 8) | buf[4];                          // p.program_number
        section_version_number = (buf[5] >> 1) & 0x1f;                  // p.version_number = getBits (b, 0, 42, 5); -> 40 + 1 -> 5 bit weit? -> version_number = buf[5] & 0x3e;
      //current_next_indicator = buf[5] & 0x01;
        section_number = buf[6];
        last_section_number = buf[7];
      //pcr_pid = ((buf[8] & 0x1f) << 8) | buf[9];
      //program_info_length = ((buf[10] & 0x0f) << 8) | buf[11];

        if (s->segmented && s->table_id_ext != -1 && s->table_id_ext != table_id_ext) {
                /* find or allocate actual section_buf matching table_id_ext */
                while (s->next_seg) {
                        s = s->next_seg;
                        if (s->table_id_ext == table_id_ext)
                                break;
                }
                if (s->table_id_ext != table_id_ext) {
                        assert(s->next_seg == NULL);
                        s->next_seg = calloc(1, sizeof(struct section_buf));
                        s->next_seg->segmented = s->segmented;
                        s->next_seg->run_once = s->run_once;
                        s->next_seg->timeout = s->timeout;
                        s = s->next_seg;
                        s->table_id = table_id;
                        s->table_id_ext = table_id_ext;
                        s->section_version_number = section_version_number;
                }
        }

        if (s->section_version_number != section_version_number ||
                        s->table_id_ext != table_id_ext) {
                struct section_buf *next_seg = s->next_seg;

                if (s->section_version_number != -1 && s->table_id_ext != -1)
                        debug("section version_number or table_id_ext changed "
                                "%d -> %d / %04x -> %04x\n",
                                s->section_version_number, section_version_number,
                                s->table_id_ext, table_id_ext);
                s->table_id_ext = table_id_ext;
                s->section_version_number = section_version_number;
                s->sectionfilter_done = 0;
                memset (s->section_done, 0, sizeof(s->section_done));
                s->next_seg = next_seg;
        }

        buf += 8;

        if (!get_bit(s->section_done, section_number)) {
                set_bit (s->section_done, section_number);

                debug("pid 0x%02x tid 0x%02x table_id_ext 0x%04x, "
                    "%i/%i (version %i)\n",
                    s->pid, table_id, table_id_ext, section_number,
                    last_section_number, section_version_number);

                switch (table_id) {
                case TABLE_PAT:
                        verbose("PAT\n");
                        parse_pat (buf, section_length, table_id_ext);
                        break;
                case TABLE_PMT:
                        verbose("PMT 0x%04x for service 0x%04x\n", s->pid, table_id_ext);
                        parse_pmt (buf, section_length, table_id_ext);
                        break;
                case TABLE_NIT_OTH:
                case TABLE_NIT_ACT:
                        verbose("NIT (%s TS)\n", table_id == 0x40 ? "actual":"other");
                        parse_nit (buf, section_length, table_id, table_id_ext);
                        break;
                case TABLE_SDT_ACT:
                case TABLE_SDT_OTH:
                        verbose("SDT (%s TS)\n", table_id == 0x42 ? "actual":"other");
                        parse_sdt (buf, section_length, table_id_ext);
                        break;
                case TABLE_VCT_TERR:
                case TABLE_VCT_CABLE:
                        verbose("ATSC VCT\n");
                        parse_psip_vct(buf, section_length, table_id, table_id_ext);
                        break;
                default:
                        ;
                }

                for (i = 0; i <= last_section_number; i++)
                        if (get_bit (s->section_done, i) == 0)
                                break;

                if (i > last_section_number)
                        s->sectionfilter_done = 1;
        }

        if (s->segmented) {
                /* always wait for timeout; this is because we don't now how
                 * many segments there are
                 */
                return 0;
        }
        else if (s->sectionfilter_done)
                return 1;

        return 0;
}


static int read_sections (struct section_buf *s)
{
        int section_length, count;

        if (s->sectionfilter_done && !s->segmented)
                return 1;

        /* the section filter API guarantess that we get one full section
         * per read(), provided that the buffer is large enough (it is)
         */
        if (((count = read (s->fd, s->buf, sizeof(s->buf))) < 0) && errno == EOVERFLOW)
                count = read (s->fd, s->buf, sizeof(s->buf));
        if (count < 0) {
                errorn("read error: (count < 0)");
                return -1;
        }

        if (count < 4)
                return -1;

        section_length = ((s->buf[1] & 0x0f) << 8) | s->buf[2];

        if (count != section_length + 3)
                return -1;

        if (parse_section(s) == 1)
                return 1;

        return 0;
}


static LIST_HEAD(running_filters);
static LIST_HEAD(waiting_filters);
static int n_running;
// see http://www.linuxtv.org/pipermail/linux-dvb/2005-October/005577.html:
// #define MAX_RUNNING 32
#define MAX_RUNNING 27

static struct pollfd poll_fds[MAX_RUNNING];
static struct section_buf* poll_section_bufs[MAX_RUNNING];


static void setup_filter (struct section_buf* s, const char *dmx_devname,
                          int pid, int table_id, int table_id_ext,
                          int run_once, int segmented) {
        memset (s, 0, sizeof(struct section_buf));

        s->fd = -1;
        s->dmx_devname = dmx_devname;
        s->pid = pid;
        s->table_id = table_id;

        s->run_once = run_once;
        s->segmented = segmented;
        if (flags.filter_timeout > 0)
                s->timeout = 5 * repetition_rate(flags.scantype, table_id);
        else
                s->timeout = repetition_rate(flags.scantype, table_id);

        s->table_id_ext = table_id_ext;
        s->section_version_number = -1;

        INIT_LIST_HEAD (&s->list);
}

static void update_poll_fds(void)
{
        struct list_head *p;
        struct section_buf* s;
        int i;

        memset(poll_section_bufs, 0, sizeof(poll_section_bufs));
        for (i = 0; i < MAX_RUNNING; i++)
                poll_fds[i].fd = -1;
        i = 0;
        list_for_each (p, &running_filters) {
                if (i >= MAX_RUNNING)
                        fatal("too many poll_fds\n");
                s = list_entry (p, struct section_buf, list);
                if (s->fd == -1)
                        fatal("s->fd == -1 on running_filters\n");
                verbosedebug("poll fd %d\n", s->fd);
                poll_fds[i].fd = s->fd;
                poll_fds[i].events = POLLIN;
                poll_fds[i].revents = 0;
                poll_section_bufs[i] = s;
                i++;
        }
        if (i != n_running)
                fatal("n_running is hosed\n");
}

static int start_filter (struct section_buf* s)
{
        struct dmx_sct_filter_params f;

        if (n_running >= MAX_RUNNING)
                goto err0;
        if ((s->fd = open (s->dmx_devname, O_RDWR)) < 0)
                goto err0;

        verbosedebug("start filter pid 0x%04x table_id 0x%02x\n", s->pid, s->table_id);

        memset(&f, 0, sizeof(f));

        f.pid = (uint16_t) s->pid;

        if (s->table_id < 0x100 && s->table_id > 0) {
                f.filter.filter[0] = (uint8_t) s->table_id;
                f.filter.mask[0]   = 0xff;
        }

        f.timeout = 0;
        f.flags = DMX_IMMEDIATE_START;

        if (ioctl(s->fd, DMX_SET_FILTER, &f) == -1) {
                errorn ("ioctl DMX_SET_FILTER failed");
                goto err1;
        }

        s->sectionfilter_done = 0;
        time(&s->start_time);

        list_del_init (&s->list);  /* might be in waiting filter list */
        list_add (&s->list, &running_filters);

        n_running++;
        update_poll_fds();

        return 0;

err1:
        ioctl (s->fd, DMX_STOP);
        close (s->fd);
err0:
        return -1;
}


static void stop_filter (struct section_buf *s)
{
        verbosedebug("stop filter pid 0x%04x\n", s->pid);
        ioctl (s->fd, DMX_STOP);
        close (s->fd);
        s->fd = -1;
        list_del (&s->list);
        s->running_time += time(NULL) - s->start_time;

        n_running--;
        update_poll_fds();
}


static void add_filter (struct section_buf *s)
{
        verbosedebug("add filter pid 0x%04x\n", s->pid);
        if (start_filter (s))
                list_add_tail (&s->list, &waiting_filters);
}


static void remove_filter (struct section_buf *s)
{
        verbosedebug("remove filter pid 0x%04x\n", s->pid);
        stop_filter (s);

        while (!list_empty(&waiting_filters)) {
                struct list_head *next = waiting_filters.next;
                s = list_entry (next, struct section_buf, list);
                if (start_filter (s))
                        break;
        }
}


static void read_filters (void)
{
        struct section_buf *s;
        int i, n, done;

        n = poll(poll_fds, n_running, 1000);
        if (n == -1)
                errorn("poll");

        for (i = 0; i < n_running; i++) {
                s = poll_section_bufs[i];
                if (!s)
                        fatal("poll_section_bufs[%d] is NULL\n", i);
                if (poll_fds[i].revents)
                        done = read_sections (s) == 1;
                else
                        done = 0; /* timeout */
                if (done || time(NULL) > s->start_time + s->timeout) {
                        if (s->run_once) {
                                if (done)
                                        verbosedebug("filter done pid 0x%04x\n", s->pid);
                                else {
                                        switch (s->table_id) {
                                          case TABLE_PAT:       info("Info: no data from PAT\n"); break;
                                          case TABLE_CAT:       info("Info: no data from CAT\n"); break;
                                          case TABLE_PMT:       info("Info: no data from PMT\n"); break;
                                          case TABLE_TSDT:      info("Info: no data from TSDT\n"); break;
                                          case TABLE_NIT_ACT:   info("Info: no data from NIT(actual)\n");break;
                                          case TABLE_NIT_OTH:   verbose("Info: no data from NIT(other)\n");break; // not always available.
                                          case TABLE_SDT_ACT:   info("Info: no data from SDT(actual)\n"); break;
                                          case TABLE_SDT_OTH:   info("Info: no data from SDT(other)\n"); break;
                                          case TABLE_BAT:       info("Info: no data from BAT\n"); break;
                                          case TABLE_EIT_ACT:   info("Info: no data from EIT(actual)\n"); break;
                                          case TABLE_EIT_OTH:   info("Info: no data from EIT(other)\n"); break;
                                          case TABLE_TDT:       info("Info: no data from TDT\n"); break;
                                          case TABLE_RST:       info("Info: no data from RST\n"); break;
                                          case TABLE_TOT:       info("Info: no data from TOT\n"); break;
                                          case TABLE_AIT:       info("Info: no data from AIT\n"); break;
                                          case TABLE_CST:       info("Info: no data from CST\n"); break;
                                          case TABLE_RCT:       info("Info: no data from RCT\n"); break;
                                          case TABLE_CIT:       info("Info: no data from CIT\n"); break;
                                          case TABLE_VCT_TERR:  info("Info: no data from VCT(terrestrial)\n"); break;
                                          case TABLE_VCT_CABLE: info("Info: no data from VCT(cable)\n"); break;
                                          default:              info("Info: no data from pid 0x%04x\n", s->pid);
                                          }
                                        }
                                remove_filter (s);
                        }
                }
        }
}


static int mem_is_zero (const void *mem, unsigned int size)
{
        const char *p = mem;
        unsigned long i;

        for (i=0; i<size; i++) {
                if (p[i] != 0x0)
                        return 0;
        }

        return 1;
}

const char * scantype_to_text (scantype_t scantype) {
        switch(scantype) {
                case SCAN_CABLE:          return "CABLE";
                case SCAN_SATELLITE:      return "SATELLITE";
                case SCAN_TERRESTRIAL:    return "TERRESTRIAL";
                case SCAN_TERRCABLE_ATSC: return "TERRCABLE_ATSC";
                default: return "UNKNOWN";
                }
}

fe_delivery_system_t atsc_del_sys(fe_modulation_t modulation) {
        switch (modulation) {
                case VSB_8:
                case VSB_16:
                        return SYS_ATSC;
                default:;
                        return SYS_DVBC_ANNEX_B;
                }
}

static int copy_fe_params(struct tuning_parameters * dest,
                          struct tuning_parameters * source) {
        memcpy (dest, source, sizeof(struct tuning_parameters));
        return 0;
}

static int set_frontend(int frontend_fd, struct transponder * t) {
        uint8_t switch_to_high_band = 0;
        uint32_t intermediate_freq = 0;
        int sequence_len = 0;
        struct dtv_property cmds[13];
        struct dtv_properties cmdseq = {0, cmds};

        info("(time: %.2d:%.2d) ", run_time() / 60, run_time() % 60);

        switch(t->type) {
                case SCAN_SATELLITE:

                        if (t->param.u.sat.modulation_system == SYS_DVBS2) {
                                if (!(fe_info.caps & FE_CAN_2G_MODULATION)) {
                                        info("\t%d: skipped (no driver support)\n", t->param.frequency/1000);
                                        return -2;
                                        }
                                }

                        if (this_lnb.high_val) {
                                if (this_lnb.switch_val) { // voltage controlled switch
                                        switch_to_high_band = 0;

                                        if (t->param.frequency >= this_lnb.switch_val)
                                                switch_to_high_band++;

                                        setup_switch (frontend_fd, committed_switch,
                                                t->param.u.sat.polarization == POLARIZATION_VERTICAL ? 0 : 1,
                                                switch_to_high_band, uncommitted_switch);

                                        usleep(50000);

                                        if (switch_to_high_band)
                                                intermediate_freq = abs(t->param.frequency - this_lnb.high_val);
                                        else
                                                intermediate_freq = abs(t->param.frequency - this_lnb.low_val);
                                        }
                                else { // C-Band Multipoint LNB
                                        if (t->param.u.sat.polarization == POLARIZATION_VERTICAL)
                                                intermediate_freq = abs(t->param.frequency - this_lnb.low_val);
                                        else
                                                intermediate_freq = abs(t->param.frequency - this_lnb.high_val);
                                        }
                                }
                        else // Monopoint LNB w/o switch
                                intermediate_freq = abs(t->param.frequency - this_lnb.low_val);

                        if ((intermediate_freq < fe_info.frequency_min) || (intermediate_freq > fe_info.frequency_max)) {
                                info ("\t skipped: (freq %u unsupported by driver)\n", intermediate_freq);
                                return -2;
                                }

                        if ((t->param.u.sat.symbol_rate < fe_info.symbol_rate_min) || (t->param.u.sat.symbol_rate > fe_info.symbol_rate_max)) {
                                info ("\tskipped: (srate %u unsupported by driver)\n", t->param.u.sat.symbol_rate);
                                return -2;
                                }

                        if (sat_list[this_channellist].rotor_position > -1) { // rotate DiSEqC rotor to correct orbital position
                                /*
                                if (t->param.u.sat.orbital_position)
                                        rotor_pos = rotor_nn(t->param.u.sat.orbital_position, t->param.u.sat.west_east_flag);
                                 */
                                if (rotate_rotor(frontend_fd, &this_rotor_pos,
                                    sat_list[this_channellist].rotor_position,
                                    t->param.u.sat.polarization == POLARIZATION_VERTICAL ? 0 : 1,
                                    switch_to_high_band))
                                        error("Error rotating rotor\n");
                                }
                        break;

                case SCAN_CABLE: // note: fall trough to TERR && ATSC
                        if ((t->param.u.cable.symbol_rate < fe_info.symbol_rate_min) || (t->param.u.cable.symbol_rate > fe_info.symbol_rate_max)) {
                                info ("\tskipped: (srate %u unsupported by driver)\n", t->param.u.cable.symbol_rate);
                                return -2;
                                }                        
                case SCAN_TERRESTRIAL:
                case SCAN_TERRCABLE_ATSC:
                        if ((t->param.frequency < fe_info.frequency_min) || (t->param.frequency > fe_info.frequency_max)) {
                                info ("\tskipped: (freq %u unsupported by driver)\n", t->param.frequency);
                                return -2;
                                }
                        break;
                default:;
                }

        if (mem_is_zero (&t->param, sizeof(struct tuning_parameters)))
                return -1;

        switch (flags.api_version) {
                case 0x0500 ... 0x05FF:
                        debug("%s: using DVB API %x.%x\n",
                          __FUNCTION__,
                         flags.api_version >> 8,
                         flags.api_version & 0xFF);

                        /* some 'shortcut' here :-)) --wk 20090324 */
                        #define set_cmd_sequence(_cmd, _data)   cmds[sequence_len].cmd = _cmd; \
                                                                cmds[sequence_len].u.data = _data; \
                                                                cmdseq.num = ++sequence_len

                        set_cmd_sequence(DTV_CLEAR, DTV_UNDEFINED);
                        switch (t->type) {
                                case SCAN_SATELLITE:
                                        set_cmd_sequence(DTV_DELIVERY_SYSTEM,   t->param.u.sat.modulation_system);
                                        set_cmd_sequence(DTV_FREQUENCY,         intermediate_freq);
                                        set_cmd_sequence(DTV_INVERSION,         t->param.inversion);
                                        set_cmd_sequence(DTV_MODULATION,        t->param.u.sat.modulation_type);
                                        set_cmd_sequence(DTV_SYMBOL_RATE,       t->param.u.sat.symbol_rate);
                                        set_cmd_sequence(DTV_INNER_FEC,         t->param.u.sat.fec_inner);
                                        set_cmd_sequence(DTV_PILOT,             t->param.u.sat.pilot);
                                        set_cmd_sequence(DTV_ROLLOFF,           t->param.u.sat.rolloff);
                                        break;
                                case SCAN_CABLE:
                                        set_cmd_sequence(DTV_DELIVERY_SYSTEM,   SYS_DVBC_ANNEX_AC);
                                        set_cmd_sequence(DTV_FREQUENCY,         t->param.frequency);
                                        set_cmd_sequence(DTV_INVERSION,         t->param.inversion);
                                        set_cmd_sequence(DTV_MODULATION,        t->param.u.cable.modulation);
                                        set_cmd_sequence(DTV_SYMBOL_RATE,       t->param.u.cable.symbol_rate);
                                        set_cmd_sequence(DTV_INNER_FEC,         t->param.u.cable.fec_inner);
                                        break;
                                case SCAN_TERRESTRIAL:
                                        set_cmd_sequence(DTV_DELIVERY_SYSTEM,   t->param.u.terr.delivery_system);
                                        if (t->param.u.terr.delivery_system == SYS_DVBT2) {
                                           set_cmd_sequence(DTV_DVBT2_PLP_ID, t->pids.plp_id);
                                           }
                                        set_cmd_sequence(DTV_FREQUENCY,         t->param.frequency);
                                        set_cmd_sequence(DTV_INVERSION,         t->param.inversion);
                                        set_cmd_sequence(DTV_BANDWIDTH_HZ,      t->param.u.terr.bandwidth);
                                        set_cmd_sequence(DTV_CODE_RATE_HP,      t->param.u.terr.code_rate_HP);
                                        set_cmd_sequence(DTV_CODE_RATE_LP,      t->param.u.terr.code_rate_LP);
                                        set_cmd_sequence(DTV_MODULATION,        t->param.u.terr.constellation);
                                        set_cmd_sequence(DTV_TRANSMISSION_MODE, t->param.u.terr.transmission_mode);
                                        set_cmd_sequence(DTV_GUARD_INTERVAL,    t->param.u.terr.guard_interval);
                                        set_cmd_sequence(DTV_HIERARCHY,         t->param.u.terr.hierarchy_information);
                                        break;
                                case SCAN_TERRCABLE_ATSC:
                                        set_cmd_sequence(DTV_DELIVERY_SYSTEM,   atsc_del_sys(t->param.u.atsc.modulation));
                                        set_cmd_sequence(DTV_FREQUENCY,         t->param.frequency);
                                        set_cmd_sequence(DTV_INVERSION,         t->param.inversion);
                                        set_cmd_sequence(DTV_MODULATION,        t->param.u.atsc.modulation);
                                        break;
                                default:
                                        fatal("Unhandled type %d\n", t->type);
                                }
                        set_cmd_sequence(DTV_TUNE, DTV_UNDEFINED);
                                                
                        if (ioctl(frontend_fd, FE_SET_PROPERTY, &cmdseq) < 0) {
                                errorn("Setting frontend parameters failed (API v5.x)\n");
                                return -1;
                                }
                        break;
                default:
                        fatal("unsupported DVB API Version %x.%x\n",
                                flags.api_version >> 8,
                                flags.api_version & 0xFF);
                }
        return 0;
}


static int __tune_to_transponder (int frontend_fd, struct transponder *t, int v) {

        fe_status_t s;
        int i, res;

        if (t == NULL)
                return -3;
        current_tp = t;
        if (current_tp->network_name != NULL) {
                free(current_tp->network_name);
                current_tp->network_name = NULL;
                }

        if ((verbosity >= 1) && (v > 0)) {
                char * buf = (char *) malloc(128); // paranoia, max = 52
                print_transponder(buf, t);
                dprintf(1, "tune to: %s %s",
                        buf, t->last_tuning_failed?" (no signal)\n":"\n");
                free(buf);
                }

        res = set_frontend(frontend_fd, t);

        if (res < 0)
                return res;

        for (i = 0; i < 5 * flags.tuning_timeout; i++) {
                usleep (200000);

                if (ioctl(frontend_fd, FE_READ_STATUS, &s) == -1) {
                        errorn("FE_READ_STATUS failed\n");
                        return -1;
                        }

                if (v > 0)
                        verbose(">>> tuning status: 0x%.2x (%s)\n",
                                s, s & FE_HAS_LOCK?  "LOCK":"NO LOCK");

                if (s & FE_HAS_LOCK) {
                        t->last_tuning_failed = 0;
                        return 0;
                        }
                }

        if (v > 0)
                info("----------no signal----------\n");
        else 
                info("\n");

        t->last_tuning_failed = 1;

        return -1;
}

static int tune_to_transponder (int frontend_fd, struct transponder *t) {
        struct list_head *pos, *tmp;
        struct transponder *check;
        int res, known = 0;
        /* move TP from "new" to "scanned" list */
        list_del_init(&t->list);

        list_for_each_safe(pos, tmp, &scanned_transponders) {
                check = list_entry (pos, struct transponder, list);
                if (is_nearly_same_frequency(check->param.frequency,t->param.frequency,t->type))
                   known = 1;
                }

        if (! known)
           list_add_tail(&t->list, &scanned_transponders);

        if (t->type != flags.scantype) {
                /* ignore cable descriptors in sat NIT and vice versa */
                t->last_tuning_failed = 1;
                return -1;
        }

        res = __tune_to_transponder (frontend_fd, t, 1);
        switch (res) {
                case 0:         return 0;
                case -1:        return __tune_to_transponder (frontend_fd, t, 1);
                case -2:        return -2;
                default:        return -1;
                }
}


static int tune_to_next_transponder (int frontend_fd)
{
        struct list_head *pos, *tmp;
        struct transponder *t;

        list_for_each_safe(pos, tmp, &new_transponders) {
                t = list_entry (pos, struct transponder, list);
retry:
                if (tune_to_transponder (frontend_fd, t) == 0)
                        return 0;
other_freq:
                if (t->other_frequency_flag &&
                                t->other_f &&
                                t->n_other_f) {
                        t->param.frequency = t->other_f[t->n_other_f - 1];
                        t->n_other_f--;
                        if (NULL == find_transponder_by_freq(t)) {
                                info("retrying with f=%d\n", t->param.frequency);
                                goto retry;
                                }
                        goto other_freq;
                }
        }
        return -1;
}


static int check_frontend (int fd, int verbose) {
        fe_status_t status;
        ioctl(fd, FE_READ_STATUS, &status);
        if (verbose) {
                uint16_t snr, signal;
                uint32_t ber, uncorrected_blocks;

                ioctl(fd, FE_READ_SIGNAL_STRENGTH, &signal);
                ioctl(fd, FE_READ_SNR, &snr);
                ioctl(fd, FE_READ_BER, &ber);
                ioctl(fd, FE_READ_UNCORRECTED_BLOCKS, &uncorrected_blocks);
                info("signal %04x | snr %04x | ber %08x | unc %08x | ", \
                                                        signal, snr, ber, uncorrected_blocks);
                if (status & FE_HAS_LOCK)
                        info("FE_HAS_LOCK");
                info("\n");
                }
        return (status & FE_HAS_LOCK) > 0;
}

static unsigned int chan_to_freq(int channel, int channellist)
{
        debug("channellist=%d, base_offset=%d, channel=%d, step=%d\n",
                channellist, base_offset(channel, channellist),
                channel, freq_step(channel, channellist));
        if (base_offset(channel, channellist) != -1) // -1 == invalid
                return base_offset(channel, channellist) +
                channel * freq_step(channel, channellist);
        return 0;
}


static int dvbc_modulation(int index)
{
        switch(index) {
                case 0:                 return QAM_64;
                case 1:                 return QAM_256;
                case 2:                 return QAM_128;                        
                default:                return QAM_AUTO;
                }
}

static int dvbc_symbolrate(int index)
{
        switch(index) { 
                // 8MHz, Rolloff 0.15 -> 8000000 / 1.15 -> symbolrate <= 6956521,74
                case 0:                 return 6900000;  // 8MHz, 6.900MSymbol/s is mostly used for 8MHz
                case 1:                 return 6875000;  // 8MHz, 6.875MSymbol/s also used quite often for 8MHz
                case 2:                 return 6956500;  // 8MHz
                case 3:                 return 6956000;  // 8MHz
                case 4:                 return 6952000;  // 8MHz
                case 5:                 return 6950000;  // 8MHz
                case 6:                 return 6790000;  // 8MHz
                case 7:                 return 6811000;  // 8MHz
                case 8:                 return 6250000;  // 8MHz
                case 9:                 return 6111000;  // 8MHz

                // 7MHz, Rolloff 0.15 -> 7000000 / 1.15 -> symbolrate <= 6086956,52
                case 10:                return 6086000;  // 8MHz, 7MHz, sort 7MHz descending by probability
                case 11:                return 5900000;  // 8MHz, 7MHz
                case 12:                return 5483000;  // 8MHz, 7MHz

                // 6MHz, Rolloff 0.15 -> 6000000 / 1.15 -> symbolrate <= 5217391,30
                case 13:                return 5217000;  // 6MHz, 7MHz, 8MHz, sort 6MHz descending by probability
                case 14:                return 5156000;  // 6MHz, 7MHz, 8MHz
                case 15:                return 5000000;  // 6MHz, 7MHz, 8MHz
                case 16:                return 4000000;  // 6MHz, 7MHz, 8MHz
                case 17:                return 3450000;  // 6MHz, 7MHz, 8MHz

                default:                return 0;
                }
}

/* called during scan loop. scans an successful tuned new transponder's
 * network information table for update of its transponder data as well as
 * other transponders announced here.
 * TODO: do similar with ATSC. mk, can you add pls?
 */
static void scan_for_other_transponders (void) {
        struct section_buf s0;
        struct section_buf s1;

        setup_filter (&s0, demux_devname, PID_NIT_ST, TABLE_NIT_ACT, -1, 1, 0);
        add_filter (&s0);
        setup_filter (&s1, demux_devname, PID_NIT_ST, TABLE_NIT_OTH, -1, 1, 1);
        add_filter (&s1);
        
        do      {
                read_filters();
                }                
        while (!(list_empty(&running_filters) && list_empty(&waiting_filters)));
}

static int initial_tune (int frontend_fd, int tuning_data)
{
uint32_t f = 0, channel, cnt, ret = 0, mod_parm, sr_parm, this_sr=0, offs;
uint16_t channel_max = 133;
struct transponder *t = NULL, *ptest;
struct transponder test;
char buffer[60];
ptest=&test;
memset(&test, 0, sizeof(test));

if (tuning_data <= 0) {

/* ---- w_scan blindscan loop ----
 *  DVB-T       : changed 20090101 -wk
 *  DVB-C       : changed 20090101 -wk
 *  DVB-S(2)    : changed 20090422 -wk
 * --
 *  ATSC part   : introduced 20080815 by mkrufky
 *                improved and Taiwan support 20081229 by mkrufky
 *                -> strongly adapted version 20090101  by wk
 */


//do last things before starting scan loop
switch (flags.scantype) {
        case SCAN_TERRCABLE_ATSC:
                switch(ATSC_type) {
                        case ATSC_VSB:
                                modulation_min=modulation_max=ATSC_VSB;
                                break;
                        case ATSC_QAM:
                                modulation_min=modulation_max=ATSC_QAM;
                                break;
                        default:
                                modulation_min=ATSC_VSB;
                                modulation_max=ATSC_QAM;
                                break;
                        }
                // disable symbolrate loop
                dvbc_symbolrate_min=dvbc_symbolrate_max=0;
                break;
        case SCAN_TERRESTRIAL:
                // disable qam loop, disable symbolrate loop
                modulation_min=modulation_max=0;
                dvbc_symbolrate_min=dvbc_symbolrate_max=0;
                break;
        case SCAN_CABLE:
                // if choosen srate is too high for channellist's bandwidth,
                // fall back to scan all srates. scan loop will skip unsupported srates later.
                if (dvbc_symbolrate(dvbc_symbolrate_min) > max_dvbc_srate(freq_step(0, this_channellist))) {
                        dvbc_symbolrate_min=0;
                        dvbc_symbolrate_max=17;
                        }
                break;
        case SCAN_SATELLITE:
                // channel means here: transponder,
                // last channel == (item_count - 1) since we're counting from 0
                channel_max = sat_list[this_channellist].item_count - 1;
                // disable qam loop
                modulation_min=modulation_max=0;
                // disable symbolrate loop
                dvbc_symbolrate_min=dvbc_symbolrate_max=0;
                // disable freq offset loop
                freq_offset_min=freq_offset_max=0;
                break;                
        default:warning("unsupported delivery system %d.\n", flags.scantype);
        }

/* ATSC VSB, ATSC QAM, DVB-T, DVB-C, DVB-S(2) here,
 * please change freqs inside country.c for ATSC, DVB-T, DVB-C
 * and inside satellites.c for DVB-S(2)
 */

for (mod_parm = modulation_min; mod_parm <= modulation_max; mod_parm++) {
   for (channel=0; channel <= channel_max; channel++) {
      for (offs = freq_offset_min; offs <= freq_offset_max; offs++)
            for (sr_parm = dvbc_symbolrate_min; sr_parm <= dvbc_symbolrate_max; sr_parm++) {                
                test.type = flags.scantype;
                switch (test.type) {
                        case SCAN_TERRESTRIAL:
                                f = chan_to_freq(channel, this_channellist);
                                if (! f) continue; //skip unused channels
                                if (freq_offset(channel, this_channellist, offs) == -1)
                                        continue; //skip this one
                                f += freq_offset(channel, this_channellist, offs);                
                                if (test.param.u.terr.bandwidth != (__u32) bandwidth(channel, this_channellist))
                                        info("Scanning %sMHz frequencies...\n",
                                        vdr_bandwidth_name(bandwidth(channel, this_channellist)));
                                test.param.frequency                    = f;
                                test.param.inversion                    = caps_inversion;
                                test.param.u.terr.bandwidth             = (__u32) bandwidth(channel, this_channellist);
                                test.param.u.terr.code_rate_HP          = caps_fec;
                                test.param.u.terr.code_rate_LP          = caps_fec;
                                test.param.u.terr.constellation         = caps_qam;
                                test.param.u.terr.transmission_mode     = caps_transmission_mode;
                                test.param.u.terr.guard_interval        = caps_guard_interval;
                                test.param.u.terr.hierarchy_information = caps_hierarchy;
                                test.param.u.terr.delivery_system       = SYS_DVBT; // DVB-T only, not T2 yet.
                                if (is_known_initial_transponder(&test,0)) {
                                        info("%d: skipped (already known transponder)\n", f/1000);
                                        continue;
                                        }
                                info("%d: ", f/1000);
                                break;
                        case SCAN_TERRCABLE_ATSC:
                                switch (mod_parm) {
                                        case ATSC_VSB:
                                                this_atsc = VSB_8;
                                                f = chan_to_freq(channel, ATSC_VSB);
                                                if (! f)
                                                        continue; //skip unused channels
                                                if (freq_offset(channel, ATSC_VSB, offs) == -1)
                                                        continue; //skip this one
                                                f += freq_offset(channel, ATSC_VSB, offs);
                                                break;
                                        case ATSC_QAM:
                                                this_atsc = QAM_256;
                                                f = chan_to_freq(channel, ATSC_QAM);
                                                if (! f)
                                                        continue; //skip unused channels
                                                if (freq_offset(channel, ATSC_QAM, offs) == -1)
                                                        continue; //skip this one
                                                f += freq_offset(channel, ATSC_QAM, offs);
                                                break;
                                        default: fatal("unknown modulation id\n");
                                        }
                                test.param.frequency            = f;
                                test.param.inversion            = caps_inversion;
                                test.param.u.atsc.modulation     = this_atsc;
                                if (is_known_initial_transponder(&test,0)) {
                                        info("%d %s: skipped (already known transponder)\n", f/1000, atsc_mod_to_txt(this_atsc));
                                        continue;
                                        }
                                info("%d: %s", f/1000, atsc_mod_to_txt(this_atsc));
                                break;
                        case SCAN_CABLE:
                                f = chan_to_freq(channel, this_channellist);
                                if (! f)
                                        continue; //skip unused channels
                                if (freq_offset(channel, this_channellist, offs) == -1)
                                        continue; //skip this one
                                f += freq_offset(channel, this_channellist, offs);
                                this_sr = dvbc_symbolrate(sr_parm);
                                if (this_sr > (uint32_t) max_dvbc_srate(freq_step(channel, this_channellist)))
                                        continue; //skip symbol rates higher than theoretical limit given by bw && roll_off
                                this_qam = caps_qam;
                                if (flags.qam_no_auto > 0) {
                                        this_qam = dvbc_modulation(mod_parm);
                                        if (test.param.u.cable.modulation != this_qam)
                                                info ("searching QAM%s...\n", vdr_modulation_name(this_qam));
                                        }
                                test.param.inversion            = caps_inversion;
                                test.param.u.cable.modulation     = this_qam;
                                test.param.u.cable.symbol_rate    = this_sr;
                                test.param.u.cable.fec_inner      = caps_fec;
                                if (f != test.param.frequency) {
                                        test.param.frequency = f;
                                        if (is_known_initial_transponder(&test,0)) {
                                                info("%d: skipped (already known transponder)\n", f/1000);
                                                continue;
                                                }
                                        info("%d: sr%d ",f/1000 , this_sr/1000); 
                                        }
                                else {
                                        if (is_known_initial_transponder(&test,0))
                                                continue;
                                        info("sr%d ", this_sr/1000);
                                        }
                                break;
                        case SCAN_SATELLITE:
                                test.param.inversion                   = caps_inversion;
                                test.param.frequency                   = sat_list[this_channellist].items[channel].intermediate_frequency * 1000;
                                test.param.u.sat.symbol_rate           = sat_list[this_channellist].items[channel].symbol_rate * 1000;
                                test.param.u.sat.fec_inner             = sat_list[this_channellist].items[channel].fec_inner;
                                test.param.u.sat.modulation_type       = sat_list[this_channellist].items[channel].modulation_type;
                                test.param.u.sat.pilot                 = PILOT_AUTO;
                                test.param.u.sat.rolloff               = sat_list[this_channellist].items[channel].rolloff;
                                test.param.u.sat.modulation_system     = sat_list[this_channellist].items[channel].modulation_system;
                                test.param.u.sat.polarization          = sat_list[this_channellist].items[channel].polarization;
                                test.param.u.sat.orbital_position      = sat_list[this_channellist].orbital_position;
                                test.param.u.sat.west_east_flag        = sat_list[this_channellist].west_east_flag;
                                if (test.param.u.sat.modulation_system == SYS_DVBS2) {
                                        if (!(fe_info.caps & FE_CAN_2G_MODULATION) ||
                                             (flags.api_version < 0x0500)) {
                                                info("%d: skipped (no driver support)\n", test.param.frequency/1000);
                                                continue;
                                                }
                                        } 
                                if (is_known_initial_transponder(&test,0)) {
                                        info("%d: skipped (already known transponder)\n", test.param.frequency/1000);
                                        continue;
                                        }
                                else {
                                        char * buf = (char *) calloc(128,1); // paranoia, max = 52
                                        print_transponder(buf, &test);
                                        info("trying '%s'\n", buf);
                                        free(buf);
                                        }
                        default:;
                        }
                if (set_frontend(frontend_fd, ptest) < 0) {
                        print_transponder(buffer, ptest);
                        dprintf(1,"\n%s:%d: Setting frontend failed %s\n",
                                __FUNCTION__, __LINE__, buffer);
                        continue;
                        }
                usleep (1000000);
                for (cnt=0;cnt<10;cnt++) {
                        ret = check_frontend(frontend_fd,0);
                        if (ret == 1) break;
                        usleep(150000);
                        }
                if (ret == 0) {
                        if (sr_parm == dvbc_symbolrate_max)
                                info("\n");
                        continue;
                        }
                if (__tune_to_transponder (frontend_fd, ptest,0) < 0)
                        continue;
                t = alloc_transponder(f);
                t->type = ptest->type;
                t->source = 0;
                copy_fe_params(&t->param, &ptest->param);
                print_transponder(buffer, t);
                info("signal ok:\n\t%s\n", buffer);
                switch (ptest->type) {
                        case SCAN_TERRCABLE_ATSC:
                                //scan_for_other_transponders(); // would this work here? Don't know, need Info!
                                break;
                        default:
                                scan_for_other_transponders(); // speed up scan NITs and later skipping known transponders.
                                break;
                        }
                break;
                }
            }        
        }

}
else {  /* ---- use initial tuning data from dvbscan ---- */
        struct list_head *pos;
        struct transponder *tp;
        info("updating transponder list..\n");
        /* tune to each channel provided and update it from
         * network information table. In parallel scan for
         * other transponders provided by NIT actual and NIT other.
         */
        list_for_each(pos, &new_transponders) {
                tp = list_entry(pos, struct transponder, list);
                print_transponder(buffer, tp);

                switch (flags.scantype) {
                        case SCAN_SATELLITE:
                                if (tp->param.u.sat.modulation_system == SYS_DVBS2) {
                                        if (!(fe_info.caps & FE_CAN_2G_MODULATION) ||
                                            (flags.api_version < 0x0500)) {
                                                info("%s: skipped (no driver support)\n", buffer);
                                                continue;
                                                }
                                        }
                                break;
                        case SCAN_TERRESTRIAL:;
                                if (tp->param.u.terr.delivery_system == SYS_DVBT2) {
                                        if (!(fe_info.caps & FE_CAN_2G_MODULATION) ||
                                            (flags.api_version < 0x0503)) {
                                                info("%s: skipped (no driver support)\n", buffer);
                                                continue;
                                                }
                                        }
                                break;
                        // may be later checks for C2 needed.
                        case SCAN_CABLE:;
                        case SCAN_TERRCABLE_ATSC:;
                        default:;
                        }

                info("%s: ", buffer);
                if (set_frontend(frontend_fd, tp) < 0) {
                        print_transponder(buffer, tp);
                        dprintf(1,"\n%s:%d: Setting frontend failed %s\n",
                                __FUNCTION__, __LINE__, buffer);
                        continue;
                        }
                usleep (1500000);
                for (cnt=0; cnt<5; cnt++) {
                        if (check_frontend(frontend_fd, 0) == 1)
                                break;
                        usleep(200000);
                        }
                if (__tune_to_transponder (frontend_fd, tp, 0) >= 0) {
                        info("signal ok\n");
                        scan_for_other_transponders();
                        }
                else
                        info("\n");
                }
        }
/* we should now have here a list of well known transponders. Iterate a second time
 * and scan it's PAT, PMT, SDT for services. In parallel NIT actual and NIT other.
 */
return tune_to_next_transponder(frontend_fd);
}

static void scan_tp_atsc(void)
{
        struct section_buf s0,s1,s2;

        if (no_ATSC_PSIP > 0) {
                setup_filter(&s0, demux_devname, PID_PAT, TABLE_PAT, -1, 1, 0); /* PAT */
                add_filter(&s0);
        } else {
                if (atsc_is_vsb(ATSC_type)) {
                        setup_filter(&s0, demux_devname, PID_VCT, TABLE_VCT_TERR, -1, 1, 0); /* terrestrial VCT */
                        add_filter(&s0);
                }
                if (atsc_is_qam(ATSC_type)) {
                        setup_filter(&s1, demux_devname, PID_VCT, TABLE_VCT_CABLE, -1, 1, 0); /* cable VCT */
                        add_filter(&s1);
                }
                setup_filter(&s2, demux_devname, PID_PAT, TABLE_PAT, -1, 1, 0); /* PAT */
                add_filter(&s2);
        }

        do {
                read_filters ();
        } while (!(list_empty(&running_filters) &&
                   list_empty(&waiting_filters)));
}

static void scan_tp_dvb (void)
{
        struct section_buf s0;
        struct section_buf s1;
        struct section_buf s2;
        struct section_buf s3;

        setup_filter (&s0, demux_devname, PID_PAT, TABLE_PAT, -1, 1, 0);
        setup_filter (&s1, demux_devname, PID_SDT_BAT_ST, TABLE_SDT_ACT, -1, 1, 0);
        setup_filter (&s2, demux_devname, PID_NIT_ST, TABLE_NIT_ACT, -1, 1, 0);

        add_filter (&s0);
        add_filter (&s1);
        add_filter (&s2);

        if (flags.get_other_nits > 0) {
           /* Note: There is more than one NIT-other: one per
            * network, separated by the network_id. */
           setup_filter (&s3, demux_devname, PID_NIT_ST, TABLE_NIT_OTH, -1, 1, 1);
           add_filter (&s3);
        }


        do {
                read_filters ();
        } while (!(list_empty(&running_filters) &&
                   list_empty(&waiting_filters)));
}

static void scan_tp(void)
{
        switch(flags.scantype) {
                case SCAN_SATELLITE:
                case SCAN_CABLE:
                case SCAN_TERRESTRIAL:
                        scan_tp_dvb();
                        break;
                case SCAN_TERRCABLE_ATSC:
                        scan_tp_atsc();
                        break;
                default:
                        warning("unimplemented scantype %d.\n", flags.scantype);
        }
}

static void network_scan (int frontend_fd, int tuning_data) {
        if (initial_tune (frontend_fd, tuning_data) < 0) {
                error("Sorry - i couldn't get any working frequency/transponder\n Nothing to scan!!\n");
                exit(1);
                }
        do {
                scan_tp();
        } while (tune_to_next_transponder(frontend_fd) == 0);
}

int device_is_preferred(int caps, const char * frontend_name, uint16_t scantype) {
        int preferred = 1; // no preferrence
        /* add other good/bad cards here. */
        if (strncmp("VLSI VES1820", frontend_name, 12) == 0)
                /* bad working FF dvb-c card, known to have qam256 probs. */
                preferred = 0; // not preferred
        else if ((strncmp("Sony CXD2820R", frontend_name, 13) == 0) && (scantype != SCAN_TERRESTRIAL))
                /* Pinnacle PCTV 290e, known to have probs on cable. */
                preferred = 0; // not preferred
        else if (caps & FE_CAN_2G_MODULATION)
                /* w_scan preferres devices which are DVB-{S,C,T}2 */
                preferred = 2; // preferred
        return preferred;        
}

int get_api_version(int frontend_fd, struct w_scan_flags * flags) {

        struct dtv_property p[] = {{.cmd = DTV_API_VERSION }};
        struct dtv_properties cmdseq = {.num = 1, .props = p};

        /* expected to fail with old drivers,
         * therefore no warning to user. 20090324 -wk
         */
        if (ioctl(frontend_fd, FE_GET_PROPERTY, &cmdseq))
           return -1;

        flags->api_version = p[0].u.data;
        return 0;
}


static void dump_lists (int adapter, int frontend)
{
        struct list_head *p1, *p2;
        struct transponder *t;
        struct service *s;
        int n = 0, i, index = 0;
        char sn[20];

        list_for_each(p1, &scanned_transponders) {
                t = list_entry(p1, struct transponder, list);
                list_for_each(p2, &t->services) {
                        s = list_entry(p2, struct service, list);
                        if (s->video_pid && !(serv_select & 1))
                                continue; /* no TV services */
                        if (!s->video_pid &&  (s->audio_num || s->ac3_num) && !(serv_select & 2))
                                continue; /* no radio services */
                        if (!s->video_pid && !(s->audio_num || s->ac3_num) && !(serv_select & 4))
                                continue; /* no data/other services */
                        if (s->scrambled && (flags.ca_select == 0))
                                continue; /* FTA only */
                        n++;
                }
        }
        info("dumping lists (%d services)\n", n);

        switch (output_format) {
                case OUTPUT_VLC_M3U:
                        vlc_xspf_prolog(stdout, adapter, frontend, &flags, &this_lnb);
                        break;
                default:;
                }

        list_for_each(p1, &scanned_transponders) {
                t = list_entry(p1, struct transponder, list);
                if (output_format == OUTPUT_DVBSCAN_TUNING_DATA && ((t->source >> 8) == 64)) {
                        dvbscan_dump_tuningdata (stdout, t, index++, &flags);
                        continue;
                        }                        
                list_for_each(p2, &t->services) {
                        s = list_entry(p2, struct service, list);

                        if (!s->service_name) { // no service name in SDT                                
                                snprintf(sn, sizeof(sn), "service_id %d", s->service_id);
                                s->service_name = strdup(sn);
                                }
                        /* ':' is field separator in vdr service lists */
                        for (i = 0; s->service_name[i]; i++) {
                                if (s->service_name[i] == ':')
                                        s->service_name[i] = ' ';
                        }
                        for (i = 0; s->provider_name && s->provider_name[i]; i++) {
                                if (s->provider_name[i] == ':')
                                        s->provider_name[i] = ' ';
                        }
                        if (s->video_pid && !(serv_select & 1))                                         // vpid, this is tv
                                continue; /* no TV services */
                        if (!s->video_pid &&  (s->audio_num || s->ac3_num) && !(serv_select & 2))       // no vpid, but apid or ac3pid, this is radio
                                continue; /* no radio services */
                        if (!s->video_pid && !(s->audio_num || s->ac3_num) && !(serv_select & 4))       // no vpid, no apid, no ac3pid, this is service/other
                                continue; /* no data/other services */
                        if (s->scrambled && (flags.ca_select == 0))                                     // caid, this is scrambled tv or radio
                                continue; /* FTA only */
                        switch (output_format) {
                          case OUTPUT_VDR:
                                vdr_dump_service_parameter_set(stdout, s, t, &flags);
                                break;
                          case OUTPUT_KAFFEINE:
                                kaffeine_dump_service_parameter_set(stdout, s, t, &flags);
                                break;
                          case OUTPUT_XINE:
                                xine_dump_service_parameter_set(stdout, s, t, &flags);
                                break;
                          case OUTPUT_MPLAYER:
                                mplayer_dump_service_parameter_set(stdout, s, t, &flags);
                                break;
                          case OUTPUT_VLC_M3U:
                                vlc_dump_service_parameter_set_as_xspf(stdout, s, t, &flags, &this_lnb);
                                break;
                          default:
                                break;
                          }
                }
        }
        switch (output_format) {
                case OUTPUT_VLC_M3U:
                        vlc_xspf_epilog(stdout);
                        break;
                default:;
                }
        info("Done.\n");
}

static void handle_sigint(int sig)
{
        error("interrupted by SIGINT, dumping partial result...\n");
        dump_lists(-1, -1);
        exit(2);
}

int fe_supports_scan(int fd, scantype_t type, struct dvb_frontend_info info) {
        struct dtv_property p[] = {{.cmd = DTV_ENUM_DELSYS }};
        struct dtv_properties cmdseq = {.num = 1, .props = p};

        if (flags.api_version >= 0x0505) {
           if (ioctl(fd, FE_GET_PROPERTY, &cmdseq) < 0)
              return 0;

           hexdump(info.name, &p[0].u.buffer.data[0], p[0].u.buffer.len);

           for (;p[0].u.buffer.len > 0; p[0].u.buffer.len--) {
               fe_delivery_system_t delsys = p[0].u.buffer.data[p[0].u.buffer.len - 1];
               switch (type) {
                      case SCAN_TERRESTRIAL:
                           if (delsys == SYS_DVBT || delsys == SYS_DVBT2)
                              return 1;
                           break;
                      case SCAN_CABLE:
                           if (delsys == SYS_DVBC_ANNEX_AC || delsys == SYS_DVBC2)
                              return 1;
                           break;
                      case SCAN_SATELLITE:
                           if (delsys == SYS_DVBS || delsys == SYS_DVBS2)
                              return 1;
                           break;
                      case SCAN_TERRCABLE_ATSC:
                           if (delsys == SYS_ATSC)
                              return 1;
                           break;
                      default: return 0;
                      }
               }
           return 0; // not found.           
           }
        else {
           debug("falling back to support outdated dvb drivers.\n");
           p[0].cmd = DTV_DELIVERY_SYSTEM;
           switch (type) {
                  case SCAN_TERRESTRIAL:    p[0].u.data = SYS_DVBT;          break;
                  case SCAN_CABLE:          p[0].u.data = SYS_DVBC_ANNEX_AC; break;
                  case SCAN_SATELLITE:      p[0].u.data = SYS_DVBS;          break;
                  case SCAN_TERRCABLE_ATSC: p[0].u.data = SYS_ATSC;          break;
                  default: return 0;
                  }
           return (ioctl(fd, FE_SET_PROPERTY, &cmdseq) == 0);
           }
        return 0; // unsupported
}

static const char *usage = "\n"
        "usage: %s [options...] \n"
        "       -f type frontend type\n"
        "               What programs do you want to search for?\n"
        "               a = atsc (vsb/qam)\n"
        "               c = cable \n"
        "               s = sat \n"
        "               t = terrestrian [default]\n"
        "       -A N    specify ATSC type\n"
        "               1 = Terrestrial [default]\n"
        "               2 = Cable\n"
        "               3 = both, Terrestrial and Cable\n"
        "       -c      choose your country here:\n"
        "                       DE, GB, US, AU, ..\n"
        "                       ? for list\n"
        "               \n"
        "       -s      choose your satellite here:\n"
        "                       S19E2, S13E0, S15W0, ..\n"
        "                       ? for list\n"
        "               ---output switches---\n"
        "       -G      generate channels.conf for dvbsrc plugin\n"
        "       -k      generate channels.dvb for kaffeine\n"
        "       -L      generate VLC xspf playlist (experimental)\n"
        "       -M      mplayer output instead of vdr channels.conf\n"
        "       -X      tzap/czap/xine output instead of vdr channels.conf\n"
        "       -x      generate initial tuning data for (dvb-)scan\n"
        "       -H      view extended help (experts only)\n";


static const char *ext_opts = "%s expert help\n"
        ".................General.................\n"
        "       -C <charset>\n"
        "               convert to charset, i.e. 'UTF-8', 'ISO-8859-15'\n"
        "               use 'iconv --list' for full list of charsets.\n"
        "       -I <file>\n"
        "               scan using dvbscan initial_tuning_data\n"
        "       -v      verbose (repeat for more)\n"
        "       -q      quiet   (repeat for less)\n"
        ".................Services................\n"
        "       -R N    radio channels\n"
        "               0 = don't search radio channels\n"
        "               1 = search radio channels [default]\n"
        "       -T N    TV channels\n"
        "               0 = don't search TV channels\n"
        "               1 = search TV channels[default]\n"
        "       -O N    Other Services\n"
        "               0 = don't search other services [default]\n"
        "               1 = search other services\n"
        "       -E N    Conditional Access (encrypted channels)\n"
        "               N=0 gets only Free TV channels\n"
        "               N=1 search also encrypted channels [default]\n"
        "       -o N    VDR version / channels.conf format\n"
        "               4 = VDR-1.4.x (depreciated)\n"
        "               6 = VDR-1.6.x (default)\n"
        "               7 = VDR-1.7.x\n"
        ".................Device..................\n"
        "       -a N    use device /dev/dvb/adapterN/ [default: auto detect]\n"
        "               (also allowed: -a /dev/dvb/adapterN/frontendM)\n"
        "       -F      use long filter timeout\n"
        "       -t N    tuning timeout\n"
        "               1 = fastest [default]\n"
        "               2 = medium\n"
        "               3 = slowest\n"
        ".................DVB-C...................\n"
        "       -i N    spectral inversion setting for cable TV\n"
        "                       (0: off, 1: on, 2: auto [default])\n"
        "       -Q      set DVB-C modulation, see table:\n"
        "                       0  = QAM64\n"
        "                       1  = QAM256\n"
        "                       2  = QAM128\n"
        "               NOTE: for experienced users only!!\n"
        "       -e      extended scan flags (DVB-C only),\n"
        "               Any combination of these flags:\n"
        "               1 = use extended symbolrate list\n"
        "                       enables scan of symbolrates\n"
        "                       6111, 6250, 6790, 6811, 5900,\n"
        "                       5000, 3450, 4000, 6950, 7000,\n"
        "                       6952, 6956, 6956.5, 5217\n"
        "               2 = extended QAM scan (enable QAM128)\n"
        "                       recommended for Nethterlands and Finland\n"
        "               NOTE: extended scan will be *slow*\n"
        "       -S      set DVB-C symbol rate, see table:\n"
        "                       0  = 6.9000 MSymbol/s\n"
        "                       1  = 6.8750 MSymbol/s\n"
        "                       2  = 6.9565 MSymbol/s\n"
        "                       3  = 6.9560 MSymbol/s\n"
        "                       4  = 6.9520 MSymbol/s\n"
        "                       5  = 6.9500 MSymbol/s\n"
        "                       6  = 6.7900 MSymbol/s\n"
        "                       7  = 6.8110 MSymbol/s\n"
        "                       8  = 6.2500 MSymbol/s\n"
        "                       9  = 6.1110 MSymbol/s\n"
        "                       10 = 6.0860 MSymbol/s\n"
        "                       11 = 5.9000 MSymbol/s\n"
        "                       12 = 5.4830 MSymbol/s\n"
        "                       13 = 5.2170 MSymbol/s\n"
        "                       14 = 5.1560 MSymbol/s\n"
        "                       15 = 5.0000 MSymbol/s\n"
        "                       16 = 4.0000 MSymbol/s\n"
        "                       17 = 3.4500 MSymbol/s\n"
        "               NOTE: for experienced users only!!\n"
        ".................DVB-S/S2................\n"
        "       -l <LNB type>\n"
        "               choose LNB type by name (DVB-S/S2 only)\n"
        "                       ? for list\n"
        "       -D Nc   use DiSEqC committed switch position N\n"
        "       -D Nu   use DiSEqC uncommitted switch position N\n"
        "       -p <file>\n"
        "               use DiSEqC rotor Position file\n"
        "       -r N use Rotor position N (needs -s)\n"
        ".................ATSC....................\n"
        "       -P      do not use ATSC PSIP tables for scanning\n"
        "               (but only PAT and PMT) (applies for ATSC only)\n";


void bad_usage(char *pname)
{
                fprintf (stderr, usage, pname);

}

void ext_help(void)
{
                fprintf (stderr, ext_opts, "w_scan");

}

#define MOD_USE_STANDARD  0x0
#define MOD_OVERRIDE_MIN  0x1
#define MOD_OVERRIDE_MAX  0x2

#define DVB_ADAPTER_MAX    32
#define DVB_ADAPTER_SCAN   16
#define DVB_ADAPTER_AUTO  999


#define cl(x)  if (x) { free(x); x=NULL; }  

int main (int argc, char **argv)
{
        char frontend_devname [80];
        int adapter = DVB_ADAPTER_AUTO, frontend = 0, demux = 0;
        int opt;
        unsigned int i = 0, j;
        int frontend_fd = -1;
        int fe_open_mode;
        uint16_t scantype = SCAN_TERRESTRIAL;
        int Radio_Services = 1;
        int TV_Services = 1;
        int Other_Services = 0; // 20080106: don't search other services by default.
        int ext = 0;
        int retVersion = 0;
        int device_preferred = -1;
        int valid_initial_data = 0;
        int valid_rotor_data = 0;
        int modulation_flags = MOD_USE_STANDARD;
        char * country = NULL;
        char * codepage = NULL;
        char * satellite = NULL;
        char * initdata = NULL;
        char * positionfile = NULL;
        char sw_type = 0;

        #define cleanup() cl(country); cl(satellite); cl(initdata); cl(positionfile); cl(codepage);

        this_lnb = * lnb_enum(0);
        this_lnb.low_val *= 1000;
        this_lnb.high_val *= 1000;
        this_lnb.switch_val *= 1000;

        flags.version = version;
        start_time = time(NULL);

        while ((opt = getopt(argc, argv, "a:c:e:f:hi:kl:o:p:qr:s:t:vxA:C:D:E:FGHI:LMO:PQ:R:S:T:VX")) != -1) {
                switch (opt) {
                case 'a': //adapter
                        if (sscanf(optarg, "%d", &adapter) < 1)
                                if (sscanf(optarg, "/dev/dvb/adapter%d/frontend%d", &adapter, &frontend) != 2
                                &&  sscanf(optarg, "/dev/virtualdvb/adapter%d/frontend%d", &adapter, &frontend) != 2)
                                        adapter = DVB_ADAPTER_AUTO, frontend = 0;
                        break;
                case 'c': //country setting
                        if (0 == strcasecmp(optarg, "?")) {
                                print_countries();
                                cleanup();
                                return(0);
                                }
                        cl(country);
                        country=strdup(optarg);
                        break;
                case 'e': //extended scan flags
                        ext = strtoul(optarg, NULL, 0);
                        if (ext & 0x01)
                                dvbc_symbolrate_max = 17;
                        if (ext & 0x02) {
                                modulation_max = 2;
                                modulation_flags |= MOD_OVERRIDE_MAX;
                                }
                        break;
                case 'f': //frontend type -> hmmm..., actually it's scan type now! 20120109, -wk-
                        if (strcmp(optarg, "t") == 0) scantype = SCAN_TERRESTRIAL;
                        if (strcmp(optarg, "c") == 0) scantype = SCAN_CABLE;
                        if (strcmp(optarg, "a") == 0) scantype = SCAN_TERRCABLE_ATSC;
                        if (strcmp(optarg, "s") == 0) scantype = SCAN_SATELLITE;
                        if (scantype == SCAN_TERRCABLE_ATSC) {
                                this_channellist = ATSC_VSB;
                                country = strdup("US");
                                }
                        break;
                case 'h': //basic help
                        bad_usage("w_scan");
                        cleanup();
                        return 0;
                        break;
                case 'i': //specify inversion
                        caps_inversion = strtoul(optarg, NULL, 0);
                        break;
                case 'k': //kaffeine output
                        output_format = OUTPUT_KAFFEINE;
                        break;
                case 'l': //satellite lnb type
                        if (strcmp(optarg, "?") == 0) {
                                struct lnb_types_st * p;
                                char ** cp;

                                while((p = lnb_enum(i++))) {
                                        info("%s\n", p->name);
                                        for (cp = p->desc; *cp;)
                                                info("\t%s\n", *cp++);
                                        }
                                cleanup();
                                return 0;
                                }
                        if (lnb_decode(optarg, &this_lnb) < 0) {
                                cleanup();
                                fatal("LNB decoding failed. Use \"-l ?\" for list.\n");
                                }
                        /* MHz -> kHz */
                        this_lnb.low_val        *= 1000;
                        this_lnb.high_val       *= 1000;
                        this_lnb.switch_val     *= 1000;
                        break;
                case 'o': //vdr Version
                        flags.vdr_version = strtoul(optarg, NULL, 0);
                        if (flags.vdr_version > 2) flags.dump_provider = 1;
                        break;
                case 'p': //satellite *p*osition file
                        positionfile=strdup(optarg);
                        break;
                case 'q': //quite
                        if (--verbosity < 0)
                                verbosity = 0;
                        break;
                case 'r': //satellite rotor position
                        flags.rotor_position = strtoul(optarg, NULL, 0);
                        break;
                case 's': //satellite setting
                        if (0 == strcasecmp(optarg, "?")) {
                                print_satellites();
                                cleanup();
                                return(0);
                                }
                        satellite=strdup(optarg);
                        break;
                case 't': //tuning speed
                        flags.tuning_timeout = strtoul(optarg, NULL, 0);
                        if ((flags.tuning_timeout < 1)) bad_usage(argv[0]);
                        if ((flags.tuning_timeout > 3)) bad_usage(argv[0]);
                        break;
                case 'v': //verbose
                        verbosity++;
                        break;
                case 'x': //dvbscan output
                        output_format = OUTPUT_DVBSCAN_TUNING_DATA;
                        break;
                case 'A': //ATSC type
                        ATSC_type = strtoul(optarg,NULL,0);
                        switch (ATSC_type) {
                          case 1: ATSC_type = ATSC_VSB; break;
                          case 2: ATSC_type = ATSC_QAM; break;
                          case 3: ATSC_type = (ATSC_VSB + ATSC_QAM); break;
                          default:
                            cleanup();
                            bad_usage(argv[0]);
                            return -1;
                          }
                        /* if -A is specified, it implies -f a */
                        scantype = SCAN_TERRCABLE_ATSC;
                        break;
                case 'C': // charset
                        codepage = strdup(optarg);
                        break;
                case 'D': //DiSEqC committed/uncommitted switch
                        sscanf(optarg,"%u%c", &i, &sw_type);
                        switch(sw_type) {
                                case 'u':
                                        uncommitted_switch = i;
                                        if (uncommitted_switch > 15)
                                                fatal("uncommitted switch position needs to be < 16!\n");
                                        flags.sw_pos = (flags.sw_pos & 0xF) | uncommitted_switch;
                                        break;
                                case 'c':
                                        committed_switch = i;
                                        if (committed_switch > 3)
                                                fatal("committed switch position needs to be < 4!\n");
                                        flags.sw_pos = (flags.sw_pos & 0xF0) | committed_switch;
                                        break;
                                default:
                                        cleanup();
                                        fatal("Could not parse Argument \"-D\"\n"
                                              "Should be number followed \"u\" or \"c\"\n");
                                }        
                        break;
                case 'E': //include encrypted channels
                        flags.ca_select = strtoul(optarg, NULL, 0);
                        break;
                case 'F': //filter timeout
                        flags.filter_timeout = 1;
                        break;
                case 'G':
                        output_format = OUTPUT_GSTREAMER;
                        break;
                case 'H': //expert help
                        ext_help();
                        cleanup();
                        return 0;
                        break;
                case 'I': //expert providing initial_tuning_data
                        initdata=strdup(optarg);
                        break;
                case 'L': //vlc output
                        output_format = OUTPUT_VLC_M3U;
                        break;
                case 'M': //mplayer output
                        output_format = OUTPUT_MPLAYER;
                        break;
                case 'O': //other services
                        Other_Services = strtoul(optarg, NULL, 0);
                        if ((Other_Services < 0)) bad_usage(argv[0]);
                        if ((Other_Services > 1)) bad_usage(argv[0]);
                        break;
                case 'P': //ATSC PSIP scan
                        no_ATSC_PSIP = 1;
                        break;
                case 'Q': //specify DVB-C QAM
                        modulation_min=modulation_max=strtoul(optarg, NULL, 0);
                        modulation_flags |= MOD_OVERRIDE_MIN;
                        modulation_flags |= MOD_OVERRIDE_MAX;
                        break;
                case 'R': //include Radio
                        Radio_Services = strtoul(optarg, NULL, 0);
                        if ((Radio_Services < 0)) bad_usage(argv[0]);
                        if ((Radio_Services > 1)) bad_usage(argv[0]);
                        break;
                case 'S': //DVB-C symbolrate index
                        dvbc_symbolrate_min=dvbc_symbolrate_max=strtoul(optarg, NULL, 0);
                        break;
                case 'T': //include TV
                        TV_Services = strtoul(optarg, NULL, 0);
                        if ((TV_Services < 0)) bad_usage(argv[0]);
                        if ((TV_Services > 1)) bad_usage(argv[0]);
                        break;
                case 'V': //Version
                        retVersion++;
                        break;
                case 'X': //xine output
                        output_format = OUTPUT_XINE;
                        break;
                default: //undefined
                        cleanup();
                        bad_usage(argv[0]);
                        return -1;
                }
        }
        if (retVersion) {
                info ("%d", version);
                cleanup();
                return 0;
                }
        info("w_scan version %d (compiled for DVB API %d.%d)\n", version, DVB_API_VERSION, DVB_API_VERSION_MINOR);
        if ((scantype == SCAN_TERRCABLE_ATSC) && (output_format == OUTPUT_VDR) && (flags.vdr_version < 7)) {
                warning("VDR up to version 1.7.13 doesn't support ATSC.\n"
                     "\tChanging output format to 'vdr-1.7.x'\n");
                flags.vdr_version = 7;
                }
        if (NULL == initdata) {
                if ((NULL == country) && (scantype != SCAN_SATELLITE)) {
                        country = strdup(country_to_short_name(get_user_country()));
                        info("guessing country '%s', use -c <country> to override\n", country);
                        }
                if ((NULL == satellite) && (scantype == SCAN_SATELLITE)) {
                        cleanup();
                        fatal("Missing argument \"-s\" (satellite setting)\n");
                        }                
                }
        serv_select = 1 * TV_Services + 2 * Radio_Services + 4 * Other_Services;
        if  (caps_inversion > INVERSION_AUTO) {
                info("Inversion out of range!\n");
                bad_usage(argv[0]);
                cleanup();
                return -1;
                }
        if  (((adapter >= DVB_ADAPTER_MAX) && (adapter != DVB_ADAPTER_AUTO)) || (adapter < 0)) {
                info("Invalid adapter: out of range (0..%d)\n", DVB_ADAPTER_MAX - 1);
                bad_usage(argv[0]);
                cleanup();
                return -1;
                }
        switch(scantype) {
                case SCAN_TERRCABLE_ATSC:
                case SCAN_CABLE:
                case SCAN_TERRESTRIAL:
                        if (country != NULL) {
                                int atsc = ATSC_type;
                                int dvb  = scantype;
                                flags.atsc_type = ATSC_type;
                                choose_country(country, &atsc, &dvb, &scantype, &this_channellist);
                                //dvbc: setting qam loop
                                if ((modulation_flags & MOD_OVERRIDE_MAX) == MOD_USE_STANDARD)
                                        modulation_max = dvbc_qam_max(2, this_channellist);
                                if ((modulation_flags & MOD_OVERRIDE_MIN) == MOD_USE_STANDARD)
                                        modulation_min = dvbc_qam_min(2, this_channellist);
                                flags.list_id = txt_to_country(country);
                                cl(country);
                                }
                        break;
                case SCAN_SATELLITE:
                        if (satellite != NULL) {
                                choose_satellite(satellite, &this_channellist);                                
                                flags.list_id = txt_to_satellite(satellite);
                                cl(satellite);
                                sat_list[this_channellist].rotor_position = flags.rotor_position;
                                }
                        else if (flags.rotor_position > -1) {
                                        cleanup();
                                        fatal("Using rotor position needs option \"-s\"\n");
                                        }
                        if (positionfile != NULL) {
                                valid_rotor_data = dvbscan_parse_rotor_positions(positionfile);
                                cl(positionfile);
                                if (! valid_rotor_data) {
                                        cleanup();
                                        fatal("could not parse rotor position file\n"
                                              "CHECK IDENTIFIERS AND FILE FORMAT.\n");
                                        }
                                }
                        break;
                default:
                        cleanup();
                        fatal("Unknown scan type %d\n", scantype);
                }

        if (initdata != NULL) {
                valid_initial_data = dvbscan_parse_tuningdata(initdata, &flags);
                cl(initdata);
                if (valid_initial_data == 0) {
                        cleanup();
                        fatal("Could not read initial tuning data. EXITING.\n");
                        }
                if (flags.scantype != scantype) {
                        warning("\n"
                                "========================================================================\n"
                                "INITIAL TUNING DATA NEEDS FRONTEND TYPE %s, YOU SELECTED TYPE %s.\n"
                                "I WILL OVERRIDE YOUR DEFAULTS TO %s\n"
                                "========================================================================\n",
                                scantype_to_text(flags.scantype),
                                scantype_to_text(scantype),
                                scantype_to_text(flags.scantype));
                        scantype = flags.scantype;                        
                        sleep(10); // enshure that user reads warning.
                        }
                }
        info("scan type %s, channellist %d\n", scantype_to_text(scantype), this_channellist);
        switch (output_format) {
                case OUTPUT_VDR:
                        info("output format vdr-1.%d\n", flags.vdr_version);
                        break;
                case OUTPUT_GSTREAMER:
                        // Gstreamer output: As vdr-1.7, but pmt_pid added at end of line.
                        flags.print_pmt = 1;
                        flags.vdr_version = 7;
                        output_format = OUTPUT_VDR;
                        info("output format gstreamer\n");
                        break;
                case OUTPUT_KAFFEINE:
                        info("output format kaffeine channels.dvb\n"); 
                        break;
                case OUTPUT_XINE:
                        info("output format czap/tzap/szap/xine\n");
                        break;
                case OUTPUT_MPLAYER:
                        info("output format mplayer\n");
                        break;
                case OUTPUT_DVBSCAN_TUNING_DATA:
                        info("output format initial tuning data\n");
                        break;
                case OUTPUT_PIDS:
                        info("output format PIDs only\n");
                        break;
                case OUTPUT_VLC_M3U:
                        info("output format vlc xspf playlist\n");
                        // vlc format will be output always as utf-8.
                        if (codepage)
                           free(codepage);
                        codepage = strdup("UTF-8");
                        break;
                default:
                        cleanup();
                        fatal("unhandled output format %d\n", output_format);
                }
        if (codepage) {
                flags.codepage = get_codepage_index(codepage);
                info("output charset '%s'\n", iconv_codes[flags.codepage]);
                }
        else {
                flags.codepage = get_user_codepage();
                info("output charset '%s', use -C <charset> to override\n", iconv_codes[flags.codepage]);
                }        
        if ( adapter == DVB_ADAPTER_AUTO ) {
                info("Info: using DVB adapter auto detection.\n");
                fe_open_mode = O_RDWR | O_NONBLOCK;
                for (i=0; i < DVB_ADAPTER_SCAN; i++) {
                  for (j=0; j < 4; j++) {
                    snprintf (frontend_devname, sizeof(frontend_devname), "/dev/dvb/adapter%i/frontend%i", i, j);
                    if ((frontend_fd = open (frontend_devname, fe_open_mode)) < 0) {
                        continue;
                        }
                    /* determine FE type and caps */
                    if (ioctl(frontend_fd, FE_GET_INFO, &fe_info) == -1) {
                        info("   ERROR: unable to determine frontend type\n");
                        close (frontend_fd);
                        continue;
                        }

                    if (flags.api_version < 0x0500)
                        get_api_version(frontend_fd, &flags);

                    if (fe_supports_scan(frontend_fd, scantype, fe_info)) {
                        info("\t%s -> %s \"%s\": ",
                                frontend_devname, scantype_to_text(scantype), fe_info.name);
                        if (device_is_preferred(fe_info.caps, fe_info.name, scantype) >= device_preferred) {
                                if (device_is_preferred(fe_info.caps, fe_info.name, scantype) > device_preferred) {
                                        device_preferred = device_is_preferred(fe_info.caps, fe_info.name, scantype);
                                        adapter=i;
                                        frontend=j;
                                        }
                                switch (device_preferred) {
                                        case 0: // device known to have probs. usable anyway..
                                                info("usable :-|\n");
                                                break;
                                        case 1: // device w/o problems
                                                info("good :-)\n");
                                                break;
                                        case 2: // perfect device found. stop scanning
                                                info("very good :-))\n\n");
                                                i=DVB_ADAPTER_AUTO;
                                                break;
                                        default:;
                                        }
                                }
                        else {
                                info("usable, but not preferred\n");
                                }
                        close (frontend_fd);
                        }
                     else {
                        info("\t%s -> \"%s\" doesnt support %s -> SEARCH NEXT ONE.\n",
                                frontend_devname,
                                fe_info.name,
                                scantype_to_text(scantype));
                        close (frontend_fd);
                        }
                    }
                }
                if (adapter < DVB_ADAPTER_AUTO) {
                        snprintf (frontend_devname, sizeof(frontend_devname), "/dev/dvb/adapter%i/frontend%i", adapter, frontend);
                        info("Using %s frontend (adapter %s)\n",
                                scantype_to_text(scantype), frontend_devname);
                        }
        }
        snprintf (frontend_devname, sizeof(frontend_devname),
                  "/dev/dvb/adapter%i/frontend%i", adapter, frontend);

        snprintf (demux_devname, sizeof(demux_devname),
                  "/dev/dvb/adapter%i/demux%i", adapter, demux);

        for (i = 0; i < MAX_RUNNING; i++)
                poll_fds[i].fd = -1;

        fe_open_mode = O_RDWR;
        if (adapter == DVB_ADAPTER_AUTO) {
                cleanup();
                fatal("***** NO USEABLE %s CARD FOUND. *****\n"
                        "Please check wether dvb driver is loaded and\n"
                        "verify that no dvb application (i.e. vdr) is running.\n",
                        scantype_to_text(scantype));
                }
        
        if ((frontend_fd = open (frontend_devname, fe_open_mode)) < 0) {
                cleanup();
                fatal("failed to open '%s': %d %s\n", frontend_devname, errno, strerror(errno));
                }
        info("-_-_-_-_ Getting frontend capabilities-_-_-_-_ \n");
        /* determine FE type and caps */
        if (ioctl(frontend_fd, FE_GET_INFO, &fe_info) == -1) {
                cleanup();
                fatal("FE_GET_INFO failed: %d %s\n", errno, strerror(errno));
                }
        flags.scantype = scantype;

        if (get_api_version(frontend_fd, &flags) < 0)
                fatal("Your DVB driver doesnt support DVB API v5. Please upgrade.\n");

        info("Using DVB API %x.%x\n",
                flags.api_version >> 8,
                flags.api_version & 0xFF);

        info("frontend '%s' supports\n", fe_info.name && *fe_info.name?fe_info.name:"<NULL pointer>");

        switch (flags.scantype) {
           case SCAN_TERRESTRIAL:
                if (fe_info.caps & FE_CAN_2G_MODULATION) {
                  info("DVB-T2\n");
                  }
                if (fe_info.caps & FE_CAN_INVERSION_AUTO) {
                  info("INVERSION_AUTO\n");
                  caps_inversion=INVERSION_AUTO;
                  }
                else {
                  info("INVERSION_AUTO not supported, trying INVERSION_OFF.\n");
                  caps_inversion=INVERSION_OFF;
                  }
                if (fe_info.caps & FE_CAN_QAM_AUTO) {
                  info("QAM_AUTO\n");
                  caps_qam=QAM_AUTO;
                  }
                else {
                  info("QAM_AUTO not supported, trying QAM_64.\n");
                  caps_qam=QAM_64;
                  }
                if (fe_info.caps & FE_CAN_TRANSMISSION_MODE_AUTO) {
                  info("TRANSMISSION_MODE_AUTO\n");
                  caps_transmission_mode=TRANSMISSION_MODE_AUTO;
                  }
                else {
                  caps_transmission_mode=dvbt_transmission_mode(5, this_channellist);
                  info("TRANSMISSION_MODE not supported, trying %s.\n",
                        xine_transmission_mode_name(caps_transmission_mode));
                  }
                if (fe_info.caps & FE_CAN_GUARD_INTERVAL_AUTO) {
                  info("GUARD_INTERVAL_AUTO\n");
                  caps_guard_interval=GUARD_INTERVAL_AUTO;
                  }
                else {
                  info("GUARD_INTERVAL_AUTO not supported, trying GUARD_INTERVAL_1_8.\n");
                  caps_guard_interval=GUARD_INTERVAL_1_8;
                  }
                if (fe_info.caps & FE_CAN_HIERARCHY_AUTO) {
                  info("HIERARCHY_AUTO\n");
                  caps_hierarchy=HIERARCHY_AUTO;
                  }
                else {
                  info("HIERARCHY_AUTO not supported, trying HIERARCHY_NONE.\n");
                  caps_hierarchy=HIERARCHY_NONE;
                  }
                if (fe_info.caps & FE_CAN_FEC_AUTO) {
                  info("FEC_AUTO\n");
                  caps_fec=FEC_AUTO;
                  }
                else {
                  info("FEC_AUTO not supported, trying FEC_NONE.\n");
                  caps_fec=FEC_NONE;
                  }
                if (fe_info.frequency_min == 0 || fe_info.frequency_max == 0) {
                  info("This dvb driver is *buggy*: the frequency limits are undefined - please report to linuxtv.org\n");
                  fe_info.frequency_min = 177500000; fe_info.frequency_min = 858000000;
                  }
                else {
                  info("FREQ (%.2fMHz ... %.2fMHz)\n", fe_info.frequency_min/1e6, fe_info.frequency_max/1e6);
                  }
                break;
           case SCAN_CABLE:
                //if (fe_info.caps & FE_CAN_2G_MODULATION) {
                //  info("DVB-C2\n");
                //  }
                if (fe_info.caps & FE_CAN_INVERSION_AUTO) {
                  info("INVERSION_AUTO\n");
                  caps_inversion=INVERSION_AUTO;
                  }
                else {
                  info("INVERSION_AUTO not supported, trying INVERSION_OFF.\n");
                  caps_inversion=INVERSION_OFF;
                  }
                if (fe_info.caps & FE_CAN_QAM_AUTO) {
                  info("QAM_AUTO\n");
                  caps_qam=QAM_AUTO;
                  }
                else {
                  info("QAM_AUTO not supported, trying");
                  //print out modulations in the sequence they will be scanned.
                  for (i = modulation_min; i <= modulation_max; i++)
                        info(" %s", xine_modulation_name(dvbc_modulation(i)));
                  info(".\n");
                  caps_qam=QAM_64;
                  flags.qam_no_auto = 1;
                  }
                if (fe_info.caps & FE_CAN_FEC_AUTO) {
                  info("FEC_AUTO\n");
                  caps_fec=FEC_AUTO;
                  }
                else {
                  info("FEC_AUTO not supported, trying FEC_NONE.\n");
                  caps_fec=FEC_NONE;
                  }
                if (fe_info.frequency_min == 0 || fe_info.frequency_max == 0) {
                  info("This dvb driver is *buggy*: the frequency limits are undefined - please report to linuxtv.org\n");
                  fe_info.frequency_min = 177500000; fe_info.frequency_max = 858000000;
                  }
                else {
                  info("FREQ (%.2fMHz ... %.2fMHz)\n", fe_info.frequency_min/1e6, fe_info.frequency_max/1e6);
                  }
                if (fe_info.symbol_rate_min == 0 || fe_info.symbol_rate_max == 0) {
                  info("This dvb driver is *buggy*: the symbol rate limits are undefined - please report to linuxtv.org\n");
                  fe_info.symbol_rate_min = 4000000; fe_info.symbol_rate_max = 7000000;
                  }
                else {
                  info("SRATE (%.3fMSym/s ... %.3fMSym/s)\n", fe_info.symbol_rate_min/1e6, fe_info.symbol_rate_max/1e6);
                  }
                break;
           case SCAN_TERRCABLE_ATSC:
                if (fe_info.caps & FE_CAN_INVERSION_AUTO) {
                  info("INVERSION_AUTO\n");
                  caps_inversion=INVERSION_AUTO;
                  }
                else {
                  info("INVERSION_AUTO not supported, trying INVERSION_OFF.\n");
                  caps_inversion=INVERSION_OFF;
                  }
                if (fe_info.caps & FE_CAN_8VSB) {
                  info("8VSB\n");
                  }
                if (fe_info.caps & FE_CAN_16VSB) {
                  info("16VSB\n");
                  }
                if (fe_info.caps & FE_CAN_QAM_64) {
                  info("QAM_64\n");
                  }
                if (fe_info.caps & FE_CAN_QAM_256) {
                  info("QAM_256\n");
                  }
                if (fe_info.frequency_min == 0 || fe_info.frequency_max == 0) {
                  info("This dvb driver is *buggy*: the frequency limits are undefined - please report to linuxtv.org\n");
                  fe_info.frequency_min = 177500000; fe_info.frequency_max = 858000000;
                  }
                else {
                  info("FREQ (%.2fMHz ... %.2fMHz)\n", fe_info.frequency_min/1e6, fe_info.frequency_max/1e6);
                  }
                break;
           case SCAN_SATELLITE:
                if (fe_info.caps & FE_CAN_INVERSION_AUTO) {
                  info("INVERSION_AUTO\n");
                  caps_inversion=INVERSION_AUTO;
                  }
                if (fe_info.caps & FE_CAN_QPSK) {
                  info("DVB-S\n");
                  caps_inversion=INVERSION_AUTO;
                  }
                if (fe_info.caps & FE_CAN_2G_MODULATION) {
                  info("DVB-S2\n");
                  caps_inversion=INVERSION_AUTO;
                  }
                if (fe_info.frequency_min == 0 || fe_info.frequency_max == 0) {
                  info("This dvb driver is *buggy*: the frequency limits are undefined - please report to linuxtv.org\n");
                  fe_info.frequency_min = 950000; fe_info.frequency_max = 2150000;
                  }
                else {
                  info("FREQ (%.2fGHz ... %.2fGHz)\n", fe_info.frequency_min/1e6, fe_info.frequency_max/1e6);
                  }
                if (fe_info.symbol_rate_min == 0 || fe_info.symbol_rate_max == 0) {
                  info("This dvb driver is *buggy*: the symbol rate limits are undefined - please report to linuxtv.org\n");
                  fe_info.symbol_rate_min = 1000000; fe_info.symbol_rate_max = 45000000;
                  }
                else {
                  info("SRATE (%.3fMSym/s ... %.3fMSym/s)\n", fe_info.symbol_rate_min/1e6, fe_info.symbol_rate_max/1e6);
                  }
                info("using LNB \"%s\"\n", this_lnb.name);
                if (committed_switch > 0)
                        info("using DiSEqC committed switch %d\n", committed_switch);
                if (uncommitted_switch > 0)
                        info("using DiSEqC uncommitted switch %d\n", uncommitted_switch);
                /* grrr...
                 * DVB API v5 doesnt allow checking for
                 * S2 capabilities fec3/5, fec9/10, PSK_8,
                 * allowed rolloff..
                 */
                break;
           default:
                cleanup();
                fatal("unsupported frontend type.\n");
           }
        info("-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ \n");

        if (! fe_supports_scan(frontend_fd, scantype, fe_info) && flags.api_version < 0x0505) {
                cleanup();
                fatal("Frontend '%s' doesnt support your choosen scan type '%s'\n",
                      fe_info.name, scantype_to_text(scantype));
                }

        signal(SIGINT, handle_sigint);

        network_scan (frontend_fd, valid_initial_data);

        close (frontend_fd);

        dump_lists (adapter, frontend);

        cleanup();

        return 0;
}