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

#include <vdr/plugin.h>
#include <vdr/filter.h>
#include <vdr/epg.h>
#include <vdr/channels.h>
#include <vdr/dvbdevice.h>
#include <vdr/i18n.h>
#include <vdr/config.h>
#include <libsi/section.h>
#include <libsi/descriptor.h>
#include <libsi/si.h>
#include "eepg.h"
#include "dish.h"
#if APIVERSNUM > 10725
#include "epghandler.h"
#endif
#include "log.h"
#include "setupeepg.h"
#include "equivhandler.h"
#include "util.h"
#include "eit2.h"

#include <map>
#include <string>
#include <stdarg.h>


#if APIVERSNUM < 10401
#error You need at least VDR API version 1.4.1 for this plugin
#endif
#if APIVERSNUM < 10507
#define trNOOP(s) (s)
#endif

#define PMT_SCAN_TIMEOUT  10 // seconds
#define PMT_SCAN_IDLE     3600 // seconds

static const char *VERSION = "0.0.6pre";
static const char *DESCRIPTION = trNOOP ("Parses Extended EPG data");

using namespace std;
using namespace util;

const char *optPats[] = {
  "%s",
  "%s (Option %d)",
  "%s (O%d)",
  "#%2$d %1$s",
  "[%2$d] %1$s"
};

#define NUM_PATS (sizeof(optPats)/sizeof(char *))

char *cs_hexdump (int m, const uchar * buf, int n)
{
  int i;
  static char dump[1024];

  dump[i = 0] = '\0';
  m = (m) ? 3 : 2;
  if (m * n >= (int) sizeof (dump))
    n = (sizeof (dump) / m) - 1;
  while (i < n)
    sprintf (dump + (m * i++), "%02X%s", *buf++, (m > 2) ? " " : "");
  return (dump);
}

cSetupEEPG* SetupPE = cSetupEEPG::getInstance();

// --- cMenuSetupPremiereEpg ------------------------------------------------------------

class cMenuSetupPremiereEpg:public cMenuSetupPage
{
private:
  cSetupEEPG* data;
  const char *optDisp[NUM_PATS];
  char buff[NUM_PATS][32];
protected:
  virtual void Store (void);
public:
  cMenuSetupPremiereEpg (void);
};

cMenuSetupPremiereEpg::cMenuSetupPremiereEpg (void)
{
  data = cSetupEEPG::getInstance();
  SetSection (tr ("PremiereEPG"));
  optDisp[0] = tr ("off");
  for (unsigned int i = 1; i < NUM_PATS; i++) {
    snprintf (buff[i], sizeof (buff[i]), optPats[i], "Event", 1);
    optDisp[i] = buff[i];
  }
  Add (new cMenuEditStraItem (tr ("Tag option events"), &data->OptPat, NUM_PATS, optDisp));
  Add (new cMenuEditBoolItem (tr ("Show order information"), &data->OrderInfo));
  Add (new cMenuEditBoolItem (tr ("Show rating information"), &data->RatingInfo));
  Add (new cMenuEditBoolItem (tr ("Fix EPG data"), &data->FixEpg));
  Add (new cMenuEditBoolItem (tr ("Display summary message"), &data->DisplayMessage));
#ifdef DEBUG
  Add (new cMenuEditIntItem (tr ("Level of logging verbosity"), &data->LogLevel, 0, 5));
  Add (new cMenuEditBoolItem (tr ("Process EIT info with EEPG"), &data->ProcessEIT));
#endif
}

void cMenuSetupPremiereEpg::Store (void)
{
  //SetupPE = data;
  SetupStore ("OptionPattern", SetupPE->OptPat);
  SetupStore ("OrderInfo", SetupPE->OrderInfo);
  SetupStore ("RatingInfo", SetupPE->RatingInfo);
  SetupStore ("FixEpg", SetupPE->FixEpg);
  SetupStore ("DisplayMessage", SetupPE->DisplayMessage);
#ifdef DEBUG
  SetupStore ("LogLevel", SetupPE->LogLevel);
  SetupStore ("ProcessEIT", SetupPE->ProcessEIT);
#endif
}

//#define Asprintf(a, b, c...) void( asprintf(a, b, c) < 0 ? esyslog("memory allocation error - %s", b) : void() )

// --- CRC16 -------------------------------------------------------------------

#define POLY 0xA001  // CRC16

unsigned int crc16 (unsigned int crc, unsigned char const *p, int len)
{
  while (len--) {
    crc ^= *p++;
    for (int i = 0; i < 8; i++)
      crc = (crc & 1) ? (crc >> 1) ^ POLY : (crc >> 1);
  }
  return crc & 0xFFFF;
}

// --- cFilterEEPG ------------------------------------------------------

#define STARTTIME_BIAS (20*60)

static int LastVersionNagra = -1; //currently only used for Nagra, should be stored per transponder, per system


class cFilterEEPG:public cFilter
{
private:
  int pmtpid, pmtsid, pmtidx, pmtnext;
  int UnprocessedFormat[HIGHEST_FORMAT + 1]; //stores the pid when a format is detected on this transponder, and that are not processed yet
  int nChannels, nThemes, nTitles, nSummaries, NumberOfTables, Version;
  int TitleCounter, SummaryCounter, NoSummaryCounter, RejectTableId;
  bool EndChannels, EndThemes; //only used for ??
  int MHWStartTime; //only used for MHW1
  bool ChannelsOk;
  //int Format; //the format that this filter currently is processing
  std::map < int, int >ChannelSeq; // ChannelSeq[ChannelId] returns the recordnumber of the channel

  Summary_t *Summaries[MAX_TITLES];
  Title_t *Titles[MAX_TITLES];
  sChannel sChannels[MAX_CHANNELS];
  unsigned char Themes[MAX_THEMES][64];

  std::map < unsigned short int, unsigned char *>buffer; //buffer[Table_Extension_Id] returns the pointer to the buffer for this TEI
  std::map < unsigned short int, int >bufsize; //bufsize[Table_Extension_Id] returns the buffersize of the buffer for this TEI
  unsigned short int NagraTIE[64]; //at this moment a max of 31 table_ids could be used, so 64 should be enough ....stores the Table_Extension_Id's of summaries received, so they can be processed. Processing while receiving somehow drops sections, the 0x0000 marker will be missed ...
  unsigned short int NagraCounter;

  unsigned char InitialChannel[8];
  unsigned char InitialTitle[64];
  unsigned char InitialSummary[64];

  void NextPmt (void);
  void ProccessContinuous(u_short Pid, u_char Tid, int Length, const u_char *Data);
protected:
  virtual void Process (u_short Pid, u_char Tid, const u_char * Data, int Length);
  virtual void AddFilter (u_short Pid, u_char Tid);
  virtual void AddFilter (u_short Pid, u_char Tid, unsigned char Mask);
  virtual void ProcessNextFormat (bool FirstTime);
  virtual int GetChannelsSKYBOX (const u_char * Data, int Length);
  virtual bool GetThemesSKYBOX (void);
  virtual int GetTitlesSKYBOX (const u_char * Data, int Length);
  virtual int GetSummariesSKYBOX (const u_char * Data, int Length);
  virtual int GetChannelsMHW (const u_char * Data, int Length, int MHW); //TODO replace MHW by Format?
  virtual int GetThemesMHW1 (const u_char * Data, int Length);
  virtual int GetNagra (const u_char * Data, int Length);
  virtual void ProcessNagra (void);
  virtual void GetTitlesNagra (const u_char * Data, int Length, unsigned short TableIdExtension);
  virtual char *GetSummaryTextNagra (const u_char * DataStart, long int Offset, unsigned int EventId);
  virtual int GetChannelsNagra (const u_char * Data, int Length);
  virtual int GetThemesNagra (const u_char * Data, int Length, unsigned short TableIdExtension);
  virtual int GetTitlesMHW1 (const u_char * Data, int Length);
  virtual int GetSummariesMHW1 (const u_char * Data, int Length);
  virtual int GetThemesMHW2 (const u_char * Data, int Length);
  virtual int GetTitlesMHW2 (const u_char * Data, int Length);
  virtual int GetSummariesMHW2 (const u_char * Data, int Length);
  virtual void FreeSummaries (void);
  virtual void FreeTitles (void);
  //virtual void PrepareToWriteToSchedule (sChannel * C, cSchedules * s, cSchedule * ps/*[MAX_EQUIVALENCES]*/); //gets a channel and returns an array of schedules that WriteToSchedule can write to. Call this routine before a batch of titles with the same ChannelId will be WriteToScheduled; batchsize can be 1
  //virtual void FinishWriteToSchedule (sChannel * C, cSchedules * s, cSchedule * ps[MAX_EQUIVALENCES]);
  virtual void WriteToSchedule (tChannelID channelID, cSchedules* s, unsigned int EventId, unsigned int StartTime,
                                unsigned int Duration, char *Text, char *SummText, unsigned short int ThemeId,
                                unsigned short int TableId, unsigned short int Version, char Rating = 0x00, unsigned char ShortTextLenght = 0);
  virtual void LoadIntoSchedule (void);
  //virtual void LoadEquivalentChannels (void);

  void ProcessPremiere(const u_char *& Data);
public:
  cFilterEEPG (void);
  virtual void SetStatus (bool On);
  void Trigger (void);
  bool InitDictionary (void); //Initialize the Huffman tables for SKY and Freesat

  static const int EIT_PID = 0x12;
};

cFilterEEPG::cFilterEEPG (void)
{
  nSummaries = 0;
  nTitles = 0;
  Trigger ();
  //Set (0x00, 0x00);
}

void cFilterEEPG::Trigger (void)
{
  LogI(3, prep("trigger\n"));
  pmtpid = 0;
  pmtidx = 0;
  pmtnext = 0;
}

void cFilterEEPG::SetStatus (bool On)
{
  LogI(0, prep("setstatus %d\n"), On);
  if (!On) {
    FreeSummaries ();
    FreeTitles ();
    //Format = 0;
    ChannelsOk = false;
    NumberOfTables = 0;
  } else {
    //Set(0x00,0x00);
    for (int i = 0; i <= HIGHEST_FORMAT; i++)
      UnprocessedFormat[i] = 0; //pid 0 is assumed to be nonvalid for EEPG transfers
    AddFilter (0, 0);
    if (Channel()->Nid() == 0x01) {
      setenv("VDR_CHARSET_OVERRIDE", "ISO-8859-9", true);
      LogD(0, prep("setenv VDR_CHARSET_OVERRIDE ISO-8859-9"));
    } else {
      unsetenv("VDR_CHARSET_OVERRIDE");
      LogD(0, prep("clear VDR_CHARSET_OVERRIDE"));
    }
  }
  cFilter::SetStatus (On);
  Trigger ();
}

void cFilterEEPG::NextPmt (void)
{
  Del (pmtpid, 0x02);
  pmtpid = 0;
  pmtidx++;
  LogE(3, prep("PMT next\n"));
}



// -------------------  Freesat -------------------

/* FreeSat Huffman decoder for VDR
 *
 * Insert GPL licence
 */

/* The following features can be controlled:
 *
 * FREEVIEW_NO_SYSLOG             - Disable use of isyslog
 */

#ifndef FREEVIEW_NO_SYSLOG
#include <vdr/tools.h>
/* Logging via vdr */
#ifndef isyslog
#define isyslog(a...) void( (SysLogLevel > 1) ? syslog_with_tid(LOG_INFO,  a) : void() )
#endif
void syslog_with_tid (int priority, const char *format, ...) __attribute__ ((format (printf, 2, 3)));
#else
#define isyslog(a...)  fprintf(stderr,a)
#endif



//struct hufftab {
//  unsigned int value;
//  short bits;
//  char next;
//};
//
//#define START   '\0'
//#define STOP    '\0'
//#define ESCAPE  '\1'


//int freesat_decode_error = 0; /* If set an error has occurred during decoding */

//static struct hufftab *tables[2][128];
//static int table_size[2][128];
static sNodeH* sky_tables[2];

/** \brief Convert a textual character description into a value
 *
 *  \param str - Encoded (in someway) string
 *
 *  \return Raw character
 */
static unsigned char resolve_char (char *str)
{
  int val;
  if (strcmp (str, "ESCAPE") == 0) {
    return ESCAPE;
  } else if (strcmp (str, "STOP") == 0) {
    return STOP;
  } else if (strcmp (str, "START") == 0) {
    return START;
  } else if (sscanf (str, "0x%02x", &val) == 1) {
    return val;
  }
  return str[0];


}


/** \brief Decode a binary string into a value
 *
 *  \param binary - Binary string to decode
 *
 *  \return Decoded value
 */
static unsigned long decode_binary (char *binary)
{
  unsigned long mask = 0x80000000;
  unsigned long maskval = 0;
  unsigned long val = 0;
  size_t i;

  for (i = 0; i < strlen (binary); i++) {
    if (binary[i] == '1') {
      val |= mask;
    }
    maskval |= mask;
    mask >>= 1;
  }
  return val;
}

/** \brief Load an individual freesat data file
 *
 *  \param tableid   - Table id that should be loaded
 *  \param filename  - Filename to load
 *  \return Success of operation
 */
static bool load_freesat_file (int tableid, const char *filename)
{
  char buf[1024];
  char *from, *to, *binary;
  FILE *fp;

  tableid--;
  if ((fp = fopen (filename, "r")) != NULL) {
    LogI(2, prep("Loading table %d Filename <%s>"), tableid + 1, filename);

    while (fgets (buf, sizeof (buf), fp) != NULL) {
      from = binary = to = NULL;
      int elems = sscanf (buf, "%a[^:]:%a[^:]:%a[^:]:", &from, &binary, &to);
      if (elems == 3) {
        int bin_len = strlen (binary);
        int from_char = resolve_char (from);
        char to_char = resolve_char (to);
        unsigned long bin = decode_binary (binary);
        int i = table_size[tableid][from_char]++;

        tables[tableid][from_char] =
          (struct hufftab *) REALLOC (tables[tableid][from_char], (i + 1) * sizeof (tables[tableid][from_char][0]));
        tables[tableid][from_char][i].value = bin;
        tables[tableid][from_char][i].next = to_char;
        tables[tableid][from_char][i].bits = bin_len;
        /* char from; unsigned int value; short bits; char next; */
        LogI(2, prep("%02x;%08x;%04x;%02x"), from_char, bin, bin_len, to_char);

        free (from);
        free (to);
        free (binary);
      }
    }
    fclose (fp);
  } else {
    LogE(0, prep("Cannot load <%s> for table %d"), filename, tableid + 1);
    return false;
  }
  return true;
}

/** \brief Load an individual freesat data file
 *
 *  \param filename  - Filename to load
 *  \return Success of operation
 */
static bool load_sky_file (const char *filename)
{
  FILE *FileDict;
  char *Line;
  char Buffer[256];
  sNodeH *nH;
  int tableId;

  FileDict = fopen (filename, "r");
  if (FileDict == NULL) {
    LogE (0, prep("Error opening file '%s'. %s"), filename, strerror (errno));
    return false;
  } else {
    int i;
    int LenPrefix;
    char string1[256];
    char string2[256];

    tableId = Format == SKY_IT ? 0 : 1;
    if (!sky_tables[tableId]) {
      sky_tables[tableId] = (sNodeH*) calloc(1,sizeof(sNodeH));
      if (!sky_tables[tableId]) {
        LogE (0, prep("Not enough memory to load file '%s'."), filename);
        return false;
      }
    }

    while ((Line = fgets (Buffer, sizeof (Buffer), FileDict)) != NULL) {
      if (!isempty (Line)) {
        memset (string1, 0, sizeof (string1));
        memset (string2, 0, sizeof (string2));
        if (sscanf (Line, "%c=%[^\n]\n", string1, string2) == 2
          || (sscanf (Line, "%[^=]=%[^\n]\n", string1, string2) == 2)) {
          nH = sky_tables[tableId];
          LenPrefix = strlen (string2);
          for (i = 0; i < LenPrefix; i++) {
            switch (string2[i]) {
            case '0':
              if (nH->P0 == NULL) {
                nH->P0 = new sNodeH ();
                nH = nH->P0;
                nH->Value = NULL;
                nH->P0 = NULL;
                nH->P1 = NULL;
                if ((LenPrefix - 1) == i) {
                  Asprintf (&nH->Value, "%s", string1);
                }
              } else {
                nH = nH->P0;
                if (nH->Value != NULL || (LenPrefix - 1) == i) {
                  LogE (0 ,prep("Error, huffman prefix code already exists for \"%s\"=%s with '%s'"), string1,
                    string2, nH->Value);
                }
              }
              break;
            case '1':
              if (nH->P1 == NULL) {
                nH->P1 = new sNodeH ();
                nH = nH->P1;
                nH->Value = NULL;
                nH->P0 = NULL;
                nH->P1 = NULL;
                if ((LenPrefix - 1) == i) {
                  Asprintf (&nH->Value, "%s", string1);
                }
              } else {
                nH = nH->P1;
                if (nH->Value != NULL || (LenPrefix - 1) == i) {
                  LogE (0, prep("Error, huffman prefix code already exists for \"%s\"=%s with '%s'"), string1,
                    string2, nH->Value);
                }
              }
              break;
            default:
              break;
            }
          }
        }
      }
    }
    fclose (FileDict);
  }

  // check tree huffman nodes
  FileDict = fopen (filename, "r");
  if (FileDict) {
    int i;
    int LenPrefix;
    char string1[256];
    char string2[256];
    while ((Line = fgets (Buffer, sizeof (Buffer), FileDict)) != NULL) {
      if (!isempty (Line)) {
        memset (string1, 0, sizeof (string1));
        memset (string2, 0, sizeof (string2));
        if (sscanf (Line, "%c=%[^\n]\n", string1, string2) == 2
          || (sscanf (Line, "%[^=]=%[^\n]\n", string1, string2) == 2)) {
          nH = sky_tables[tableId];
          LenPrefix = strlen (string2);
          for (i = 0; i < LenPrefix; i++) {
            switch (string2[i]) {
            case '0':
              if (nH->P0 != NULL) {
                nH = nH->P0;
              }
              break;
            case '1':
              if (nH->P1 != NULL) {
                nH = nH->P1;
              }
              break;
            default:
              break;
            }
          }
          if (nH->Value != NULL) {
            if (memcmp (nH->Value, string1, strlen (nH->Value)) != 0) {
              LogE (0, prep("Error, huffman prefix value '%s' not equal to '%s'"), nH->Value, string1);
            }
          } else {
            LogE (0, prep("Error, huffman prefix value is not exists for \"%s\"=%s"), string1, string2);
          }
        }
      }
    }
    fclose (FileDict);
  }
  return true;
}

/** \brief Decode an EPG string as necessary
 *
 *  \param src - Possibly encoded string
 *  \param size - Size of the buffer
 *
 *  \retval NULL - Can't decode
 *  \return A decoded string
 */
char *freesat_huffman_decode (const unsigned char *src, size_t size)
{
  int tableid;
//  freesat_decode_error = 0;

  if (src[0] == 0x1f && (src[1] == 1 || src[1] == 2)) {
    int uncompressed_len = 30;
    char *uncompressed = (char *) calloc (1, uncompressed_len + 1);
    unsigned value = 0, byte = 2, bit = 0;
    int p = 0;
    unsigned char lastch = START;

    tableid = src[1] - 1;
    while (byte < 6 && byte < size) {
      value |= src[byte] << ((5 - byte) * 8);
      byte++;
    }
    //freesat_table_load ();    /**< Load the tables as necessary */

    do {
      bool found = false;
      unsigned bitShift = 0;
      if (lastch == ESCAPE) {
        char nextCh = (value >> 24) & 0xff;
        found = true;
        // Encoded in the next 8 bits.
        // Terminated by the first ASCII character.
        bitShift = 8;
        if ((nextCh & 0x80) == 0)
          lastch = nextCh;
        if (p >= uncompressed_len) {
          uncompressed_len += 10;
          uncompressed = (char *) REALLOC (uncompressed, uncompressed_len + 1);
        }
        uncompressed[p++] = nextCh;
        uncompressed[p] = 0;
      } else {
        int j;
        for (j = 0; j < table_size[tableid][lastch]; j++) {
          unsigned mask = 0, maskbit = 0x80000000;
          short kk;
          for (kk = 0; kk < tables[tableid][lastch][j].bits; kk++) {
            mask |= maskbit;
            maskbit >>= 1;
          }
          if ((value & mask) == tables[tableid][lastch][j].value) {
            char nextCh = tables[tableid][lastch][j].next;
            bitShift = tables[tableid][lastch][j].bits;
            if (nextCh != STOP && nextCh != ESCAPE) {
              if (p >= uncompressed_len) {
                uncompressed_len += 10;
                uncompressed = (char *) REALLOC (uncompressed, uncompressed_len + 1);
              }
              uncompressed[p++] = nextCh;
              uncompressed[p] = 0;
            }
            found = true;
            lastch = nextCh;
            break;
          }
        }
      }
      if (found) {
        // Shift up by the number of bits.
        unsigned b;
        for (b = 0; b < bitShift; b++) {
          value = (value << 1) & 0xfffffffe;
          if (byte < size)
            value |= (src[byte] >> (7 - bit)) & 1;
          if (bit == 7) {
            bit = 0;
            byte++;
          } else
            bit++;
        }
      } else {
        LogE (0, prep("Missing table %d entry: <%s>"), tableid + 1, uncompressed);
        // Entry missing in table.
        return uncompressed;
      }
    } while (lastch != STOP && value != 0);

    return uncompressed;
  }
  return NULL;
}

int sky_huffman_decode (const u_char * Data, int Length, unsigned char *DecodeText)
{
  sNodeH *nH, H=(Format==SKY_IT)?*sky_tables[0]:*sky_tables[1];
  int i;
  int p;
  int q;
  bool CodeError;
  bool IsFound;
  unsigned char Byte;
  unsigned char lastByte;
  unsigned char Mask;
  unsigned char lastMask;
  nH = &H;
  p = 0;
  q = 0;
  DecodeText[0] = '\0';
  //DecodeErrorText[0] = '\0';
  CodeError = false;
  IsFound = false;
  lastByte = 0;
  lastMask = 0;
  for (i = 0; i < Length; i++) {
    Byte = Data[i];
    Mask = 0x80;
    if (i == 0) {
      Mask = 0x20;
      lastByte = i;
      lastMask = Mask;
    }
loop1:
    if (IsFound) {
      lastByte = i;
      lastMask = Mask;
      IsFound = false;
    }
    if ((Byte & Mask) == 0) {
      if (CodeError) {
        //DecodeErrorText[q] = 0x30;
        q++;
        goto nextloop1;
      }
      if (nH->P0 != NULL) {
        nH = nH->P0;
        if (nH->Value != NULL) {
          memcpy (&DecodeText[p], nH->Value, strlen (nH->Value));
          p += strlen (nH->Value);
          nH = &H;
          IsFound = true;
        }
      } else {
        memcpy (&DecodeText[p], "<...?...>", 9);
        p += 9;
        i = lastByte;
        Byte = Data[lastByte];
        Mask = lastMask;
        CodeError = true;
        goto loop1;
      }
    } else {
      if (CodeError) {
        //DecodeErrorText[q] = 0x31;
        q++;
        goto nextloop1;
      }
      if (nH->P1 != NULL) {
        nH = nH->P1;
        if (nH->Value != NULL) {
          memcpy (&DecodeText[p], nH->Value, strlen (nH->Value));
          p += strlen (nH->Value);
          nH = &H;
          IsFound = true;
        }
      } else {
        memcpy (&DecodeText[p], "<...?...>", 9);
        p += 9;
        i = lastByte;
        Byte = Data[lastByte];
        Mask = lastMask;
        CodeError = true;
        goto loop1;
      }
    }
nextloop1:
    Mask = Mask >> 1;
    if (Mask > 0) {
      goto loop1;
    }
  }
  DecodeText[p] = '\0';
  //DecodeErrorText[q] = '\0';
  return p;
}

//here all declarations for global variables over all devices

//char *ConfDir;

//unsigned char DecodeErrorText[4096];  //TODO only used for debugging?

bool cFilterEEPG::GetThemesSKYBOX (void) //TODO can't we read this from the DVB stream?
{
  string FileName = cSetupEEPG::getInstance()->getConfDir();
  FILE *FileThemes;
  char *Line;
  char Buffer[256];
  if (Format == SKY_IT)
    FileName += "/sky_it.themes";
  else if (Format == SKY_UK)
    FileName += "/sky_uk.themes";
  else {
    LogE (0, prep("Error, wrong format detected in GetThemesSKYBOX. Format = %i."), Format);
    return false;
  }
  //asprintf( &FileName, "%s/%s", ConfDir, ( lProviders + CurrentProvider )->Parm3 );
  FileThemes = fopen (FileName.c_str(), "r");
  if (FileThemes == NULL) {
    LogE (0, prep("Error opening file '%s'. %s"), FileName.c_str(), strerror (errno));
    return false;
  } else {
    //int id = 0;
    nThemes = 0;
    char string1[256];
    char string2[256];
    //sTheme *T;
    while ((Line = fgets (Buffer, sizeof (Buffer), FileThemes)) != NULL) {
      memset (string1, 0, sizeof (string1));
      memset (string2, 0, sizeof (string2));
      if (!isempty (Line)) {
        //T = &Themes[nThemes];
        if (sscanf (Line, "%[^=] =%[^\n] ", string1, string2) == 2) {
          snprintf ((char *) Themes[nThemes], 255, "%s", string2);
        } else {
          Themes[nThemes][0] = '\0';
        }
        //id ++;
        nThemes++;
      }
    }
    fclose (FileThemes);
  }
  return true;
}

/**
 * \brief Initialize the Huffman dictionaries if they are not already initialized.
 *
 */
bool cFilterEEPG::InitDictionary (void)
{
  string FileName = cSetupEEPG::getInstance()->getConfDir();
  switch (Format) {
  case SKY_IT:
    if (sky_tables[0] == NULL) {
      FileName += "/sky_it.dict";
      LogD (4, prep("EEPGDebug: loading sky_it.dict"));
      return load_sky_file(FileName.c_str());
    } else
        LogD (4, prep("EEPGDebug: sky_it.dict already loaded"));
    break;
  case SKY_UK:
    if (sky_tables[1] == NULL) {
      FileName += "/sky_uk.dict";
      LogD (4, prep("EEPGDebug: loading sky_uk.dict"));
      return load_sky_file(FileName.c_str());
    } else
        LogD (4, prep("EEPGDebug: sky_uk.dict already loaded"));
    break;
  case FREEVIEW:
    if (tables[0][0] == NULL) {
      LogD (4, prep("EEPGDebug: loading freesat.dict"));
      FileName += "/freesat.t1";
      if (!load_freesat_file (1, FileName.c_str()))
        return false;
      FileName = cSetupEEPG::getInstance()->getConfDir();
      FileName += "/freesat.t2";
      return load_freesat_file (2, FileName.c_str());
    } else
        LogD (4, prep("EEPGDebug: freesat.dict already loaded"));
    break;
  default:
    LogE (0 ,prep("Error, wrong format detected in ReadFileDictionary. Format = %i."), Format);
    return false;
  }
  return true;
}

//void decodeText2 (const unsigned char *from, int len, char *buffer, int buffsize)
//{
//  if (from[0] == 0x1f) {
//    char *temp = freesat_huffman_decode (from, len);
//    if (temp) {
//      len = strlen (temp);
//      len = len < buffsize - 1 ? len : buffsize - 1;
//      strncpy (buffer, temp, len);
//      buffer[len] = 0;
//      free (temp);
//      return;
//    }
//  }
//
//  SI::String convStr;
//  SI::CharArray charArray;
//  charArray.assign(from, len);
//  convStr.setData(charArray, len);
//  //LogE(5, prep("decodeText2 from %s - length %d"), from, len);
//  convStr.getText(buffer,  buffsize);
//  //LogE(5, prep("decodeText2 buffer %s - buffsize %d"), buffer, buffsize);
//}

/**
 * \brief Get MHW channels
 *
 * \return 0 = fatal error, code 1 = success, code 2 = last item processed
 */
int cFilterEEPG::GetChannelsMHW (const u_char * Data, int Length, int MHW)
{
  if ((MHW == 1) || (nChannels == 0)) { //prevents MHW2 from reading channels twice while waiting for themes on same filter
    sChannelMHW1 *Channel;
    int Size, Off;
    Size = sizeof (sChannelMHW1);
    Off = 4;
    if (MHW == 1) {
      //Channel = (sChannelMHW1 *) (Data + 4);
      nChannels = (Length - Off) / sizeof (sChannelMHW1);
    }
    if (MHW == 2) {
      if (Length > 120)
        nChannels = Data[120];
      else {
        LogE(0, prep("Error, channels packet too short for MHW2."));
        return 0;
      }
      int pName = ((nChannels * 8) + 121);
      if (Length > pName) {
        //Channel = (sChannelMHW1 *) (Data + 120);
        Size -= 14; //MHW2 is 14 bytes shorter
        Off = 121;  //and offset differs
      } else {
        LogE(0, prep("Error, channels length does not match pname."));
        return 0;
      }
    }

    if (nChannels > MAX_CHANNELS) {
      LogE(0, prep("EEPG: Error, %i channels found more than %i"), nChannels, MAX_CHANNELS);
      return 0;
    } else {
      LogI(1, "|  ID  | %-26.26s | %-22.22s | FND | %-8.8s |\n", "Channel ID", "Channel Name", "Sky Num.");
      LogI(1, "|------|-%-26.26s-|-%-22.22s-|-----|-%-8.8s-|\n", "------------------------------",
           "-----------------------------", "--------------------");
      int pName = ((nChannels * 8) + 121); //TODO double ...
      for (int i = 0; i < nChannels; i++) {
        Channel = (sChannelMHW1 *) (Data + Off);
        sChannel *C = &sChannels[i];
        C->ChannelId = i;
        ChannelSeq[C->ChannelId] = i; //fill lookup table to go from channel-id to sequence nr in table
        C->SkyNumber = 0;
        if (MHW == 1)
          memcpy (C->Name, &Channel->Name, 16); //MHW1
        else {   //MHW2
          int lenName = Data[pName] & 0x0f;
          //LogD (1, prep("EEPGDebug: MHW2 lenName:%d"), lenName);
          decodeText2(&Data[pName+1],lenName,(char*)C->Name,256);
          //memcpy (C->Name, &Data[pName + 1], lenName);
          //else
          //memcpy (C->Name, &Data[pName + 1], 256);
          pName += (lenName + 1);
        }
        //C->NumberOfEquivalences = 1; //there is always an original channel. every equivalence adds 1
        C->Src = Source (); //assume all EPG channels are on same satellite, if not, manage this via equivalents!!!
        C->Nid = HILO16 (Channel->NetworkId);
        C->Tid = HILO16 (Channel->TransportId);
        C->Sid = HILO16 (Channel->ServiceId);
        tChannelID channelID = tChannelID (C->Src, C->Nid, C->Tid, C->Sid);
        cChannel *VC = GetChannelByID(channelID, true);
        bool IsFound = (VC);
        if(IsFound) {
          C->Src = VC->Source();
        }
        CleanString (C->Name);

        LogI(1, "|% 5d | %-26.26s | %-22.22s | %-3.3s |  % 6d  |\n", C->ChannelId
             , *tChannelID (C->Src, C->Nid, C->Tid, C->Sid).ToString()
             , C->Name, IsFound ? "YES" : "NO", C->SkyNumber);

        Off += Size;
      } //for loop
    }   //else nChannels > MAX_CHANNELS
    //LoadEquivalentChannels ();
    EquivHandler->loadEquivalentChannelMap();
    GetLocalTimeOffset (); //reread timing variables, only used for MHW
    return 2; //obviously, when you get here, channels are read successfully, but since all channels are sent at once, you can stop now
  } //if nChannels == 0
  LogE (0, prep("Warning: Trying to read Channels more than once!"));
  //you will only get here when GetChannelsMHW is called, and nChannels !=0, e.g. when multiple citpids cause channels to be read multiple times. Second time, do nothing, give error so that the rest of the chain is not restarted also.
  return 0;
}

/**
 * \brief Get MHW1 Themes
 *
 * \return 0 = fatal error, code 1 = success, code 2 = last item processed
 */
int cFilterEEPG::GetThemesMHW1 (const u_char * Data, int Length)
{ //MHW1 Themes
  if (Length > 19) {
    sThemeMHW1 *Theme = (sThemeMHW1 *) (Data + 19);
    nThemes = (Length - 19) / 15;
    if (nThemes > MAX_THEMES) {
      LogE(1, prep("Error, %i themes found more than %i"), nThemes, MAX_THEMES);
      return 0;
    } else {
      LogI(1, "-------------THEMES FOUND--------------");
      int ThemeId = 0;
      int Offset = 0;
      const u_char *ThemesIndex = (Data + 3);
      for (int i = 0; i < nThemes; i++) {
        if (ThemesIndex[ThemeId] == i) {
          Offset = (Offset + 15) & 0xf0; //TODO do not understand this
          ThemeId++;
        }
        memcpy (&Themes[Offset][0], &Theme->Name, 15);
        Themes[Offset][15] = '\0'; //trailing null
        CleanString (Themes[Offset]);
        LogI(1, prep("%.15s"), Themes[Offset]);
        Offset++;
        Theme++;
      }
      if ((nThemes * 15) + 19 != Length) {
        LogE(0, "Themes error: buffer is smaller or bigger than sum of entries.");
        return 0;
      } else
        return 2;
    }
  }
  return 1;
}

/**
 * \brief Get MHW2 Themes
 *
 * \return 0 = fatal error, code 1 = success, code 2 = last item processed
 */
int cFilterEEPG::GetThemesMHW2 (const u_char * Data, int Length)
{
  if (!EndThemes) { //only process if not processed
    int p1;
    int p2;
    int pThemeName = 0;
    int pSubThemeName = 0;
    int lenThemeName = 0;
    int lenSubThemeName = 0;
    int pThemeId = 0;
    if (Length > 4) {
      LogI(1, "-------------THEMES FOUND--------------");
      for (int i = 0; i < Data[4]; i++) {
        p1 = ((Data[5 + i * 2] << 8) | Data[6 + i * 2]) + 3;
        if (Length > p1) {
          for (int ii = 0; ii <= (Data[p1] & 0x3f); ii++) {
            p2 = ((Data[p1 + 1 + ii * 2] << 8) | Data[p1 + 2 + ii * 2]) + 3;
            if (Length > p2) {
              if (ii == 0) {
                pThemeName = p2 + 1;
                lenThemeName = Data[p2] & 0x1f;
                lenSubThemeName = 0;
              } else {
                pSubThemeName = p2 + 1;
                lenSubThemeName = Data[p2] & 0x1f;
              }
              if (Length >= (pThemeName + lenThemeName)) {
                pThemeId = ((i & 0x3f) << 6) | (ii & 0x3f);
                if (pThemeId > MAX_THEMES) {
                  LogE(1, prep("Error, something wrong with themes id calculation MaxThemes: %i pThemeID:%d"), MAX_THEMES, pThemeId);
                  return 0; //fatal error
                }
                if ((lenThemeName + 2) < 256) {
                  decodeText2(&Data[pThemeName],lenThemeName,(char*)Themes[pThemeId],256);
                  //memcpy (Themes[pThemeId], &Data[pThemeName], lenThemeName);
                  if (Length >= (pSubThemeName + lenSubThemeName))
                    if (lenSubThemeName > 0)
                      if ((lenThemeName + lenSubThemeName + 2) < 256) {
                        Themes[pThemeId][lenThemeName] = '-';
                        decodeText2(&Data[pSubThemeName],lenSubThemeName,(char*)&Themes[pThemeId][lenThemeName + 1],256);
                        //memcpy (&Themes[pThemeId][lenThemeName + 1], &Data[pSubThemeName], lenSubThemeName);
                      }
                  CleanString (Themes[pThemeId]);
                  LogI(1, prep("%.*s"), lenThemeName + 1 + lenSubThemeName, Themes[pThemeId]);
                  //isyslog ("%.15s", (lThemes + pThemeId)->Name);
                  nThemes++;
                  if (nThemes > MAX_THEMES) {
                    LogE(1, prep("Error, %i themes found more than %i"), nThemes, MAX_THEMES);
                    return 0; //fatal error
                  }
                }
              } else
                return 1; //I assume non fatal error or success
            } else
              return 1;  //I assume non fatal error or success
          }
        } else
          return 1;  //I assume non fatal error or success
      }    //for loop
      //Del (Pid, Tid);
      EndThemes = true;
      return 2; //all themes read
    } //if length
  } //if !EndThemes
  return 1; //non fatal or success
}

/**
 * \brief Get Nagra Summary text
 *
 * \param TitleEventId EventId passed from title, to check it against the eventId of the summary
 * \return pointer to reserved part of memory with summary text in it, terminated by NULL
 */
char *cFilterEEPG::GetSummaryTextNagra (const u_char * DataStart, long int Offset, unsigned int TitleEventId)
//EventId is passed from title, to check it against the eventid of the summary
{
  u_char *p = (u_char *) DataStart + Offset;
  sSummaryDataNagraGuide *SD = (sSummaryDataNagraGuide *) p;

  if (TitleEventId != HILO32 (SD->EventId)) {
    LogI(0, prep("ERROR, Title has EventId %08x and points to Summary with EventId %08x."), TitleEventId,
      HILO32 (SD->EventId));
    return 0; //return empty string
  }

  if (CheckLevel(3)) {
    if (SD->AlwaysZero1 != 0)
      isyslog ("EEPGDEBUG: SummAlwaysZero1 is NOT ZERO:%x.", SD->AlwaysZero1);
    if (SD->AlwaysZero2 != 0)
      isyslog ("EEPGDEBUG: SummAlwaysZero2 is NOT ZERO:%x.", SD->AlwaysZero2);
    if (SD->AlwaysZero3 != 0)
      isyslog ("EEPGDEBUG: SummAlwaysZero3 is NOT ZERO:%x.", SD->AlwaysZero3);
    if (SD->AlwaysZero4 != 0)
      isyslog ("EEPGDEBUG: SummAlwaysZero4 is NOT ZERO:%x.", SD->AlwaysZero4);
    if (SD->AlwaysZero5 != 0)
      isyslog ("EEPGDEBUG: SummAlwaysZero5 is NOT ZERO:%x.", SD->AlwaysZero5);
    if (SD->AlwaysZero6 != 0)
      isyslog ("EEPGDEBUG: SummAlwaysZero6 is NOT ZERO:%x.", SD->AlwaysZero6);
    if (SD->AlwaysZero7 != 0)
      isyslog ("EEPGDEBUG: SummAlwaysZero7 is NOT ZERO:%x.", SD->AlwaysZero7);
    if (SD->AlwaysZero8 != 0)
      isyslog ("EEPGDEBUG: SummAlwaysZero8 is NOT ZERO:%x.", SD->AlwaysZero8);
    if (SD->AlwaysZero9 != 0)
      isyslog ("EEPGDEBUG: SummAlwaysZero9 is NOT ZERO:%x.", SD->AlwaysZero9);

    if (SD->Always1 != 0x31) //1970
      isyslog ("EEPGDEBUG: SummAlways1:%02x.", SD->Always1);
    if (SD->Always9 != 0x39)
      isyslog ("EEPGDEBUG: SummAlways9:%02x.", SD->Always9);
    if (SD->Always7 != 0x37)
      isyslog ("EEPGDEBUG: SummAlways7:%02x.", SD->Always7);
    if (SD->Always0 != 0x30)
      isyslog ("EEPGDEBUG: SummAlways0:%02x.", SD->Always0);

    if (SD->Always0x01 != 0x01) // 0x01 byte
      isyslog ("EEPGDEBUG: Summ0x01 byte:%02x.", SD->Always0x01);
  }
  u_char *p2 = (u_char *) DataStart + HILO32 (SD->SummTxtOffset);
  /*    esyslog
        ("EEPGDEBUG: EventId %08x NumberOfBlocks %02x BlockId %08x SummTxtOffset %08x *p2: %02x Unkn1:%02x, Unkn2:%02x.",
         HILO32 (SD->EventId), SD->NumberOfBlocks, HILO32 (SD->BlockId), HILO32 (SD->SummTxtOffset), *p2, SD->Unknown1,
         SD->Unknown2);
   */
  unsigned char *Text = NULL; //makes first realloc work like malloc
  int TotLength = 0; //and also makes empty summaries if *p2 != 0x4e
  if (SD->NumberOfBlocks > 1) {
    switch (*p2) {
    case 0x4e: //valid summary text follows
    {
      bool LastTextBlock = false;

      do { //for all text parts
        sSummaryTextNagraGuide *ST = (sSummaryTextNagraGuide *) p2;
        p2 += 8;  //skip fixed block
        if (ST->AlwaysZero1 != 0)
          LogD(3, prep("DEBUG: ST AlwaysZero1 is NOT ZERO:%x."), ST->AlwaysZero1);
        if (ST->Always0x4e != 0x4e) {
          LogI(0, prep("DEBUG: ST Always0x4e is NOT 0x4e:%x."), ST->AlwaysZero1);
          return 0; //fatal error, empty text
        }
        LogI(5, prep("DEBUG: Textnr %i, Lasttxt %i."), ST->TextNr, ST->LastTextNr);
        int SummaryLength = ST->Textlength;

        Text = (unsigned char *) REALLOC (Text, SummaryLength + TotLength);
        if (Text == NULL) {
          LogI(0, prep("Summaries memory allocation error."));
          return 0; //empty text
        }
        memcpy (Text + TotLength, p2, SummaryLength); //append new textpart
        TotLength += SummaryLength;
        p2 += ST->Textlength; //skip text

        LastTextBlock = ((ST->LastTextNr == 0) || (ST->TextNr >= ST->LastTextNr));
      } while (!LastTextBlock);
      Text = (unsigned char *) REALLOC (Text, 1 + TotLength); //allocate 1 extra byte
      Text[TotLength] = '\0'; //terminate string by NULL char
      LogD(5, prep("DEBUG: Full Text:%s."), Text);

      break;
    }
    case 0x8c: //"Geen uitzending" "Geen informatie beschikbaar" e.d.
    {
      sSummaryGBRNagraGuide *GBR = (sSummaryGBRNagraGuide *) p2;

      p2 += 16; //skip fixed part, point to byte after Nextlength
      if (CheckLevel(3)) {
        if (GBR->AlwaysZero1 != 0)
          isyslog ("EEPGDEBUG: GBR AlwaysZero1 is NOT ZERO:%x.", GBR->AlwaysZero1);
        if (GBR->AlwaysZero2 != 0)
          isyslog ("EEPGDEBUG: GBR AlwaysZero2 is NOT ZERO:%x.", GBR->AlwaysZero2);
        if (GBR->AlwaysZero3 != 0)
          isyslog ("EEPGDEBUG: GBR AlwaysZero3 is NOT ZERO:%x.", GBR->AlwaysZero3);
        if (GBR->AlwaysZero4 != 0)
          isyslog ("EEPGDEBUG: GBR AlwaysZero4 is NOT ZERO:%x.", GBR->AlwaysZero4);

        isyslog ("EEPGDEBUG: Blocklength: %02x Data %02x %02x %02x %02x %02x %02x %02x %02x %02x", GBR->Blocklength,
                 GBR->Un1, GBR->Un2, GBR->Un3, GBR->Un4, GBR->Un5, GBR->Un6, GBR->Un7, GBR->Un8, GBR->Un9);
        for (int i = 0; i < GBR->Nextlength; i += 2)
          isyslog ("GBR Extradata %02x %02x.", *(p2 + i), *(p2 + i + 1));
      }
    }
    break;
    default:
      LogE(0, prep("ERROR *p2 has strange value: EventId %08x NumberOfBlocks %02x BlockId %08x SummTxtOffset %08x *p2: %02x Unkn1:%02x, Unkn2:%02x."),
        HILO32 (SD->EventId), SD->NumberOfBlocks, HILO32 (SD->BlockId), HILO32 (SD->SummTxtOffset), *p2,
        SD->Unknown1, SD->Unknown2);
      break;
    } //end of switch
  } //NrOfBlocks > 1

  if (TotLength == 0)
    Text = NULL;

  p += 29; //skip fixed part of block
  if (SD->NumberOfBlocks == 1)
    p -= 4; //in this case there is NO summary text AND no GBR??!!
  for (int i = 1; i < (SD->NumberOfBlocks - 1); i++) {
    LogD(3, prep("DEBUG: Extra Block info: %02x %02x %02x %02x."), *p, *(p + 1), *(p + 2), *(p + 3));
    p += 4; //skip this extra block info
  }
  return (char *) Text;
}

/**
 * \brief Prepare to Write to Schedule
 *
 * gets a channel and returns an array of schedules that WriteToSchedule can write to.
 * Call this routine before a batch of titles with the same ChannelId will be WriteToScheduled; batchsize can be 1
 *
 * \param C channel to prepare
 * \param s VDR epg schedules
 * \param ps pointer to the schedules that WriteToSchedule can write to
 */
//void cFilterEEPG::PrepareToWriteToSchedule (sChannel * C, cSchedules * s, cSchedule * ps/*[MAX_EQUIVALENCES]*/)
//{
//  //for (int eq = 0; eq < C->NumberOfEquivalences; eq++) {
//    tChannelID channelID = tChannelID (C->Src/*[eq]*/, C->Nid/*[eq]*/, C->Tid/*[eq]*/, C->Sid/*[eq]*/);
//#ifdef USE_NOEPG
//    if (allowedEPG (channelID) && (channelID.Valid ()))
//#else
//    if (channelID.Valid ()) //only add channels that are known to vdr
//#endif /* NOEPG */
//      ps/*[eq]*/ = s->AddSchedule (channelID); //open a a schedule for each equivalent channel
//    else {
//      ps/*[eq]*/ = NULL;
////      LogE(5, prep("ERROR: Title block has invalid (equivalent) channel ID: Equivalence: %i, Source:%x, C->Nid:%x,C->Tid:%x,C->Sid:%x."),
////           eq, C->Src[eq], C->Nid[eq], C->Tid[eq], C->Sid[eq]);
//    }
//  //}
//}

//void cFilterEEPG::FinishWriteToSchedule (sChannel * C, cSchedules * s, cSchedule * ps[MAX_EQUIVALENCES])
//{
//  for (int eq = 0; eq < C->NumberOfEquivalences; eq++)
//    if (ps[eq]) {
//      ps[eq]->Sort ();
//      s->SetModified (ps[eq]);
//    }
//}

/**
 * \brief write event to schedule
 *
 * \param Duration the Duration of the event in minutes
 * \param ps points to array of schedules ps[eq], where eq is equivalence number of the channel. If channelId is invalid then ps[eq]=NULL
 */
void cFilterEEPG::WriteToSchedule(tChannelID channelID, cSchedules* pSchedules,
    unsigned int EventId, unsigned int StartTime, unsigned int Duration,
    char *Text, char *SummText, unsigned short int ThemeId,
    unsigned short int TableId, unsigned short int Version, char Rating,
    unsigned char ShTxtLen)
{
  bool WrittenTitle = false;
  bool WrittenSummary = false;
//  for (int eq = 0; eq < NumberOfEquivalences; eq++) {
  cSchedule* ps;
  if (channelID.Valid ()) //only add channels that are known to VDR
    ps = pSchedules->AddSchedule (channelID); //open or create new schedule
  else {
    ps = NULL;
  }

  cEvent *Event = NULL;
  if (ps/*[eq]*/) {

      Event = (cEvent *) ps->GetEvent (EventId); //since Nagra uses consistent EventIds, try this first
      bool TableIdMatches = false;
      if (Event)
        TableIdMatches = (Event->TableID() == TableId);
      if (!Event || !TableIdMatches || abs(Event->StartTime() - (time_t) StartTime) > Duration * 60) //if EventId does not match, or it matched with wrong TableId, then try with StartTime
        Event = (cEvent *) ps->GetEvent (EventId, StartTime);
  }
  cEvent *newEvent = NULL;
  if (!Event) {  //event is new
    Event = newEvent = new cEvent (EventId);
    Event->SetSeen ();
  } else if (Event->TableID() < TableId) { //existing table may not be overwritten
    RejectTableId++;
    //esyslog ("EEPGDEBUG: Rejecting Event, existing TableID:%x, new TableID:%x.", Event->TableID (),
    //           TableId);
    Event = NULL;
  }

  if (Event) {
    Event->SetEventID (EventId); //otherwise the summary cannot be added later
    Event->SetTableID (TableId); //TableID 0 is reserved for external epg, will not be overwritten; the lower the TableID, the more actual it is
    Event->SetVersion (Version); //TODO use version and tableID to decide whether to update; TODO add language code
    Event->SetStartTime (StartTime);
    Event->SetDuration (Duration * 60);
    if (Rating) {
      Event->SetParentalRating(Rating);
    }
    if (Text != 0x00) {
      WrittenTitle = true;
      CleanString ((uchar *) Text);
      Event->SetTitle (Text);
    }

    char *tmp = NULL;
    string shText;
    if (SummText && ShTxtLen) {
    
      shText.assign(SummText,ShTxtLen);

      string tmpTitle(Text);
      if (Format == MHW2 && !shText.empty()) {
        //TODO (HD) channels
        size_t found = tmpTitle.find(" (HD)");
        if (found != string::npos)
          tmpTitle.erase(found, 5);
        found = shText.compare(0, tmpTitle.size() + 2, string(tmpTitle + ": "));
        if (shText.compare(0, tmpTitle.size() + 2, string(tmpTitle + ": "))==0)
          shText.erase(0, tmpTitle.size() + 2);
      }

     //Do not use Subtitle if it is substring of Title
      if (tmpTitle.compare(0, shText.size(), shText) == 0)
        shText.clear();

#define MAX_USEFUL_EPISODE_LENGTH 40
      // From VDR FixEPG Bugs
      // Some channels put a whole lot of information in the ShortText and leave
      // the Description totally empty. So if the ShortText length exceeds
      // MAX_USEFUL_EPISODE_LENGTH, let's put this into the Description
      // instead:
      if (!shText.empty() && shText.size() > MAX_USEFUL_EPISODE_LENGTH)
        shText.clear();

    }
    if (!shText.empty())
      Event->SetShortText (shText.c_str());
    else {
      Asprintf (&tmp, "%s - %d\'", Themes[ThemeId], Duration);
      Event->SetShortText (tmp);
      free(tmp);
    }
/*
    char *tmp;
    if (!ShortText || strcmp(ShortText, Text) == 0) {
      Asprintf (&tmp, "%s - %d\'", Themes[ThemeId], Duration);
      Event->SetShortText (tmp);
      free(tmp);
    } else
      Event->SetShortText (ShortText);
*/
    //strreplace(t, '|', '\n');
    if (SummText != 0x00) {
      WrittenSummary = true;
      CleanString ((uchar *) SummText);

      //Add themes and categories epgsearch style
      //TODO DPE move this
      char *theme;
      Asprintf (&theme, "%s", Themes[ThemeId]);
      if (theme && 0 != strcmp(theme,"")) {
        char *category, *genre;
        category = NULL;
        genre = NULL;
        char *split = strchr(theme, '-'); // Look for '-' delim to separate category from genre
        if (split){
          *split = 0;
          category = theme;
          genre = (split[1] == 0x20) ? split + 2 : split + 1;
        }else{
          category = theme;
        }
        string fmt;
        fmt = "%s";
        if (stripspace(category)) {
          fmt += "\nCategory: %s";
        }
        if (genre) {
          fmt += "\nGenre: %s";
        }
        Asprintf (&tmp, fmt.c_str(), SummText, category, stripspace (genre));

        Event->SetDescription (tmp);
        free(tmp);
        free(theme);
    }
    else
      Event->SetDescription (SummText);
    }
    if (ps && newEvent)
      ps->AddEvent (newEvent);

    EquivHandler->updateEquivalent(pSchedules, channelID, Event);

    if (!ps) {
    //the event is not send to VDR so it has to be deleted.
      delete Event;
      Event = NULL;
    }

    //newEvent->FixEpgBugs (); causes segfault
  }
      /*      else
            esyslog ("EEPG: ERROR, somehow not able to add/update event.");*///at this moment only reports RejectTableId events
  if (CheckLevel(4)) {
    isyslog ("EEPG: Title:%i, Summary:%i I would put into schedule:", TitleCounter, SummaryCounter);
    //isyslog ("C %s-%i-%i-%i\n", *cSource::ToString (C->Src[eq]), C->Nid[eq], C->Tid[eq], C->Sid[eq]);
    isyslog ("E %u %u %u 01 FF\n", EventId, StartTime, Duration * 60);
    isyslog ("T %s\n", Text);
    isyslog ("S %s - %d\'\n", Themes[ThemeId], Duration);
    isyslog ("D %s\n", SummText);
    isyslog ("e\nc\n.\n");
  }
//    } //if ps[eq]
//  } //for eq
  if (WrittenTitle)
    TitleCounter++;
  if (WrittenSummary)
    SummaryCounter++;
}

/**
 * \brief  Get Nagra titles
 *
 * \param TableIdExtension the TIE from the relevant summary sections!
 */
void cFilterEEPG::GetTitlesNagra (const u_char * Data, int Length, unsigned short TableIdExtension)
{
  u_char *p = (u_char *) Data;
  u_char *DataEnd = (u_char *) Data + Length;
  u_char *next_p;
  unsigned short int MonthdayTitles = ((TableIdExtension & 0x1ff) >> 4); //Day is coded in day of the month
  time_t timeLocal;
  struct tm *tmCurrent;

  timeLocal = time (NULL);
  tmCurrent = gmtime (&timeLocal); //gmtime gives UTC; only used for getting current year and current day of the month...
  unsigned short int CurrentMonthday = tmCurrent->tm_mday;
  unsigned short int CurrentYear = tmCurrent->tm_year;
  unsigned short int CurrentMonth = tmCurrent->tm_mon;
  //esyslog("EEPGDEBUG: CurrentMonthday=%i, TableIdExtension:%04x, MonthdayTitles=%i.",CurrentMonthday,TableIdExtension, MonthdayTitles);
  cSchedulesLock SchedulesLock (true);
  cSchedules *s = (cSchedules *) cSchedules::Schedules (SchedulesLock);
  do { //process each block of titles
    sTitleBlockNagraGuide *TB = (sTitleBlockNagraGuide *) p;
    int ChannelId = HILO16 (TB->ChannelId);
    int Blocklength = HILO16 (TB->Blocklength);
    long int NumberOfTitles = HILO32 (TB->NumberOfTitles);

    LogD(3, prep("DEBUG: ChannelId %04x, Blocklength %04x, NumberOfTitles %lu."), ChannelId, Blocklength,
         NumberOfTitles);
    p += 4; //skip ChannelId and Block length
    next_p = p + Blocklength;
    if (next_p > DataEnd) { //only process if block is complete
      LogE(0, prep("ERROR, Block exceeds end of Data. p:%p, Blocklength:%x,DataEnd:%p."), p, Blocklength, DataEnd);
      return; //fatal error, this should never happen
    }
    p += 4; //skip Title number

    sChannel *C = &sChannels[ChannelSeq[ChannelId]]; //find channel
    //cSchedule *ps = NULL;//[MAX_EQUIVALENCES];
    //PrepareToWriteToSchedule (C, s, ps);

    for (int i = 0; i < NumberOfTitles; i++) { //process each title within block
      sTitleNagraGuide *Title = (sTitleNagraGuide *) p;
      unsigned int EventId = HILO32 (Title->EventId);

      unsigned int StartTime = Title->StartTimeHigh << 5 | Title->StartTimeLow;
      int Hours = (StartTime / 60);
      int Minutes = StartTime % 60;

      /*StartTime */
      tmCurrent->tm_year = CurrentYear;
      tmCurrent->tm_mon = CurrentMonth;
      tmCurrent->tm_mday = MonthdayTitles;
      tmCurrent->tm_hour = 0;
      tmCurrent->tm_min = StartTime; //if start time is bigger than 1 hour, mktime will correct this!
      tmCurrent->tm_sec = 0;
      tmCurrent->tm_isdst = -1; //now correct with daylight savings
      if (MonthdayTitles < CurrentMonthday - 7) //the titles that are older than one week are not from the past, but from next month!
        //at first this was set at -1 day (= yesterday), but sometimes providers send old data which then
        //end up in next months schedule ...
        tmCurrent->tm_mon++; //if a year border is passed, mktime will take care of this!
      StartTime = UTC2LocalTime (mktime (tmCurrent)); //VDR stores its times in UTC, but wants its input in local time...

      char *Text = NULL;
      u_char *t = (u_char *) Data + HILO32 (Title->OffsetToText);
      //u_char *t2 = (u_char *) Data + HILO32 (Title->OffsetToText2);
      if (t >= DataEnd)
        LogE(0, prep("ERROR, Title Text out of range: t:%p, DataEnd:%p, Data:%p, Length:%i."), t, DataEnd, Data,
          Length);
      else {
        Asprintf (&Text, "%.*s", *t, t + 1);
        //asprintf (&Text, "%.*s %.*s", *t, t + 1, *t2, t2 + 1); //FIXME second text string is not processed right now

        //now get summary texts
        u_char *DataStartSummaries = buffer[TableIdExtension] + 4;
        unsigned int DataLengthSummaries = bufsize[TableIdExtension] - 4;
        char *SummText = NULL;
        if (HILO32 (Title->SumDataOffset) >= DataLengthSummaries)
          LogE(0, prep("ERROR, SumDataOffset out of range: Title->SumDataOffset:%i, DataLengthSummaries:%i."), HILO32 (Title->SumDataOffset),DataLengthSummaries);
        else
          SummText = GetSummaryTextNagra (DataStartSummaries, HILO32 (Title->SumDataOffset), EventId);

        LogD(3, prep("DEBUG: Eventid: %08x ChannelId:%x, Start time %02i:%02i, Duration %i, OffsetToText:%08x, OffsetToText2:%08x, SumDataOffset:%08x ThemeId:%x Title:%s \n SummaryText:%s"),
             EventId, ChannelId, Hours, Minutes, Title->Duration,
             HILO32 (Title->OffsetToText), HILO32 (Title->OffsetToText2),
             HILO32 (Title->SumDataOffset), Title->ThemeId, Text, SummText);

        if (Themes[Title->ThemeId][0] == 0x00) //if detailed themeid is not known, get global themeid
          Title->ThemeId &= 0xf0;

        WriteToSchedule (tChannelID (C->Src, C->Nid, C->Tid, C->Sid), s, EventId, StartTime, Title->Duration, Text, SummText,
                         Title->ThemeId, NAGRA_TABLE_ID, Version);

        if (Text != NULL)
          free (Text);
        Text = NULL;
        if (SummText != NULL)
          free (SummText);
        SummText = NULL;
      }

      if (CheckLevel(3)) {
        if (Title->AlwaysZero16 != 0)
          isyslog ("EEPGDEBUG: TitleAlwaysZero16 (3bits) is NOT ZERO:%x.", Title->AlwaysZero16);
        if (Title->AlwaysZero17 != 0)
          isyslog ("EEPGDEBUG: TitleAlwaysZero17 is NOT ZERO:%x.", Title->AlwaysZero17);
        if (Title->AlwaysZero1 != 0)
          isyslog ("EEPGDEBUG: TitleAlwaysZero1 is NOT ZERO:%x.", Title->AlwaysZero1);
        if (Title->AlwaysZero2 != 0)
          isyslog ("EEPGDEBUG: TitleAlwaysZero2 is NOT ZERO:%x.", Title->AlwaysZero2);
        if (Title->AlwaysZero3 != 0)
          isyslog ("EEPGDEBUG: TitleAlwaysZero3 is NOT ZERO:%x.", Title->AlwaysZero3);
        if (Title->AlwaysZero4 != 0)
          isyslog ("EEPGDEBUG: TitleAlwaysZero4 is NOT ZERO:%x.", Title->AlwaysZero4);
        if (Title->AlwaysZero5 != 0)
          isyslog ("EEPGDEBUG: TitleAlwaysZero5 is NOT ZERO:%x.", Title->AlwaysZero5);
        if (Title->AlwaysZero8 != 0)
          isyslog ("EEPGDEBUG: TitleAlwaysZero8 is NOT ZERO:%x.", Title->AlwaysZero8);
        if (Title->AlwaysZero9 != 0)
          isyslog ("EEPGDEBUG: TitleAlwaysZero9 is NOT ZERO:%x.", Title->AlwaysZero9);
        if (Title->AlwaysZero10 != 0)
          isyslog ("EEPGDEBUG: TitleAlwaysZero10 is NOT ZERO:%x.", Title->AlwaysZero10);
        if (Title->AlwaysZero11 != 0)
          isyslog ("EEPGDEBUG: TitleAlwaysZero11 is NOT ZERO:%x.", Title->AlwaysZero11);
      }
      p += 30; //next title
    } //end for titles

    //FinishWriteToSchedule (C, s, ps);
    sortSchedules(s, tChannelID (C->Src, C->Nid, C->Tid, C->Sid));
    p = next_p;
  } while (p < DataEnd); //end of TitleBlock
}

int cFilterEEPG::GetThemesNagra (const u_char * Data, int Length, unsigned short TableIdExtension) //return code 0 = fatal error, code 1 = success, code 2 = last item processed
{
  u_char *DataStart = (u_char *) Data;
  u_char *p = DataStart; //TODO Language code terminated by 0 is ignored
  u_char *DataEnd = DataStart + Length;
  u_char *DataStartTitles = buffer[TableIdExtension] + 4;
  u_char *DataEndTitles = DataStartTitles + bufsize[TableIdExtension] - 4;
  if (Length == 0) {
    LogI(1, prep("NO THEMES FOUND"));
    return 2;
  }

  int NumberOfThemes = (*p << 24) | *(p + 1) << 16 | *(p + 2) << 8 | *(p + 3);
  p += 4; //skip number of themes block
  //isyslog ("EEPG: found %i themes.", NumberOfThemes);

  if ((nThemes == 0))
    LogI(1, "-------------THEMES FOUND--------------");

  for (int i = 0; i < NumberOfThemes; i++) {
    int Textlength = *p;
    p++; //skip textlength byte
    u_char *Text = p;
    u_char ThemeId = 0;
    p += Textlength; //skip text
    int NrOfBlocks = (*p << 8) | *(p + 1);
    p += 2; //skip nrofblocks
    bool AnyDoubt = false;
    u_char *p2 = p;
    p += NrOfBlocks * 8;
    for (int j = 0; j < NrOfBlocks; j++) {
      sThemesTitlesNagraGuide *TT = (sThemesTitlesNagraGuide *) p2;
      p2 += 8; //skip block
      u_char *NewThemeId = DataStartTitles + HILO32 (TT->TitleOffset) + 28;
      if (NewThemeId >= DataEndTitles)
        LogE(0, prep("ERROR, ThemeId out of range: NewThemeId:%p, DataEndTitles:%p, DataStartTitles:%p."), NewThemeId,
          DataEndTitles, DataStartTitles);
      else {
        //esyslog("EEPGDEBUG: NewThemeId:%02x, Text:%s.",*NewThemeId, Text);
        if (Themes[*NewThemeId][0] != 0x00) { //theme is already filled, break off
          AnyDoubt = true;
          break;
        }
        if (j == 0) //first block
          ThemeId = *NewThemeId;
        else if (ThemeId != *NewThemeId) { //different theme ids in block
          if ((ThemeId & 0xf0) != (*NewThemeId & 0xf0)) { //major nible of themeid does not correspond
            LogE(3, prep("ERROR, Theme has multiple indices which differ in major nibble, old index = %x, new index = %x. Ignoring both indices."),
              ThemeId, *NewThemeId);
            AnyDoubt = true;
            break;
          } else if ((ThemeId & 0x0f) != 0) //ThemeId is like 1a, 2a, not like 10,20. So it is minor in tree-structure, and it should be labeled in major part of tree
            ThemeId = *NewThemeId; //lets hope new themeid is major, if not, it has not worsened....
        }
      }    //else NewThemeId >= DataEndTitles
      if (CheckLevel(3)) {
        if (TT->Always1 != 1)
          isyslog ("EEPGDEBUG: TT Always1 is NOT 1:%x.", TT->Always1);
        if (TT->AlwaysZero1 != 0)
          isyslog ("EEPGDEBUG: TT AlwaysZero1 is NOT ZERO:%x.", TT->AlwaysZero1);
        if (TT->AlwaysZero2 != 0)
          isyslog ("EEPGDEBUG: TT AlwaysZero2 is NOT ZERO:%x.", TT->AlwaysZero2);
      }
    } //for nrofblocks
    // esyslog("EEPGDEBUG: AnyDoubt:%x.",AnyDoubt);
    if (!AnyDoubt) {
      if (Textlength > 63)
        Textlength = 63; //leave room for trailing NULL
      if (Themes[ThemeId][0] != 0) {
        LogE(0, prep("Trying to add new theme, but Id already exists. ThemeId = %x, Old theme with this Id:%s, new theme: %s."),
          ThemeId, Themes[ThemeId], Text);
        continue;
      }
      memcpy (&Themes[ThemeId], Text, Textlength);
      Themes[ThemeId][Textlength] = '\0'; //trailing NULL
      CleanString (Themes[ThemeId]);
      nThemes++;
      LogI(1, prep("%02x %s"), ThemeId, Themes[ThemeId]);
    }
  } //for NumberOfThemes
  if (p != DataEnd) {
    LogE(0, prep("Themes error: buffer is smaller or bigger than sum of entries. p:%p,DataEnd:%p"), p, DataEnd);
    return 0;
  } else
    return 2;
}

/**
 * \brief Get Nagra channels
 *
 * \return 0 = fatal error, code 1 = success, code 2 = last item processed
 */
int cFilterEEPG::GetChannelsNagra (const u_char * Data, int Length)
{
  u_char *DataStart = (u_char *) Data;
  u_char *p = DataStart;
  u_char *DataEnd = DataStart + Length;

  nChannels = (*p << 24) | *(p + 1) << 16 | *(p + 2) << 8 | *(p + 3);
  p += 4; //skip numberofchannels
  if (CheckLevel(1)) {
    isyslog ("|  ID  | %-26.26s | %-22.22s | FND | %-8.8s |\n", "Channel ID", "Channel Name", "Sky Num.");
    isyslog ("|------|-%-26.26s-|-%-22.22s-|-----|-%-8.8s-|\n", "------------------------------",
             "-----------------------------", "--------------------");
  }

  for (int j = 0; j < nChannels; j++) {
    sChannelsNagraGuide *Channel = (sChannelsNagraGuide *) p;
    sChannel *C = &sChannels[j];
    C->ChannelId = j + 1; //Nagra starts numbering at 1
    ChannelSeq[C->ChannelId] = j; //fill lookup table to go from channel-id to sequence nr in table; lookup table starts with 0
    C->SkyNumber = 0;
    //C->NumberOfEquivalences = 1; //there is always an original channel. every equivalence adds 1
    C->Src = Source(); //assume all EPG channels are on same satellite, if not, manage this via equivalents!!!
    C->Nid = HILO16 (Channel->NetworkId);
    C->Tid = HILO16 (Channel->TransportId);
    C->Sid = HILO16 (Channel->ServiceId);
    tChannelID channelID = tChannelID(C->Src, C->Nid, C->Tid, C->Sid);
    cChannel *VC = GetChannelByID(channelID, true);
    bool IsFound = (VC);
    if(IsFound) {
      strncpy((char*)(C->Name), VC->Name (), 64);
      C->Src = VC->Source();
      CleanString (C->Name);
    }
    else
      C->Name[0] = '\0'; //empty string

    LogI(1, "|% 5d | %-26.26s | %-22.22s | %-3.3s |  % 6d  |\n", C->ChannelId
         , *channelID.ToString(), C->Name, IsFound ? "YES" : "NO", C->SkyNumber);

    LogD(4, prep("DEBUG: start    : %s"), cs_hexdump (0, p, 9));

    p += 8; //skip to first 0x8c if non-FTA, or 0x00 if FTA
    for (int i = 0; i < Channel->Nr8cBlocks; i++) {
      if (*p != 0x8c) {
        LogD(0, prep("DEBUG: ERROR in Channel Table, expected value of 0x8c is %02x"), *p);
        return 0; //fatal error
      }
      p++; //skip 8c byte
      LogD(4, prep("DEBUG: 8c string: %s"), cs_hexdump (0, p + 1, *p));
      p += *p; //skip 8c block
      p++; //forgot to skip length byte
    }
    //start last non 8c block here
    if (*p != 0x00) {
      LogE(0, prep("ERROR in Channel Table, expected value of 0x00 is %02x"), *p);
      return 0; //fatal error
    }
    p++; //skip 0x00 byte
    LogD(4, prep("DEBUG: endstring: %s"), cs_hexdump (0, p + 1, *p * 4));
    p += (*p * 4); //p points to nrofblocks, each block is 4 bytes
    p++; //forgot to skip nrofblocks byte

    /*
        if (Channel->AlwaysZero1 != 0)
          isyslog ("EEPGDEBUG: AlwaysZero1 is NOT ZERO:%x.", Channel->AlwaysZero1);
        if (Channel->AlwaysZero2 != 0)
          isyslog ("EEPGDEBUG: AlwaysZero2 is NOT ZERO:%x.", Channel->AlwaysZero2);
        if (Channel->Always0x8c != 0x8c)
          isyslog ("EEPGDEBUG: Always0x8c is NOT 0x8c:%x.", Channel->Always0x8c);
        if (Channel->Always0x08 != 0x08)
          isyslog ("EEPGDEBUG: Always0x08 is NOT 0x08:%x.", Channel->Always0x08);
        if (Channel->Always0x02 != 0x02)
          isyslog ("EEPGDEBUG: Always0x02 is NOT 0x02:%x.", Channel->Always0x02);
        if (Channel->Always0x01 != 0x01)
          isyslog ("EEPGDEBUG: Always0x01 is NOT 0x01:%x.", Channel->Always0x01);
        if (Channel->Always0x20 != 0x20)
          isyslog ("EEPGDEBUG: Always0x20 is NOT 0x20:%x.", Channel->Always0x20);
        if (Channel->Always0x0a != 0x0a)
          isyslog ("EEPGDEBUG: Always0x0a is NOT 0x0a:%x.", Channel->Always0x0a);
        if (Channel->Always0x81 != 0x81)
          isyslog ("EEPGDEBUG: Always0x81 is NOT 0x81:%x.", Channel->Always0x81);
        if (Channel->Always0x44 != 0x44)
          isyslog ("EEPGDEBUG: Always0x44 is NOT 0x44:%x.", Channel->Always0x44);
     */

  }
  if (p != DataEnd)
    LogE(0, prep("Warning, possible problem at end of channel table; p = %p, DataEnd = %p"), p, DataEnd);
  //LoadEquivalentChannels ();
  EquivHandler->loadEquivalentChannelMap();
  return 2; //obviously, when you get here, channels are read succesfully, but since all channels are sent at once, you can stop now
}

/**
 * \brief Get Nagra extended EPG
 *
 * \return 0 = fatal error, code 1 = success, code 2 = last item processed
 */
int cFilterEEPG::GetNagra (const u_char * Data, int Length)
{
  sTitleBlockHeaderNagraGuide *TBH = (sTitleBlockHeaderNagraGuide *) Data;
  if (InitialTitle[0] == 0x00) { //InitialTitle is empty, so we are waiting for the start marker
    if (TBH->TableIdExtensionHigh == 0x00 && TBH->TableIdExtensionLow == 0x00) { //this is the start of the data
      if (TBH->VersionNumber == LastVersionNagra) {
        LogI(0, prep("Nagra EEPG already up-to-date with version %i"), LastVersionNagra);
        return 2;
      }
      Version = TBH->VersionNumber;
      LogI(0, prep("initialized Nagraguide, version %i"), Version);
      //u_char *p = (u_char *) Data + 11;
      u_char *p = (u_char *) Data + 8;
      if (*p != 0x01) {
        LogE(0, prep("Error, Nagra first byte in table_id_extension 0x00 is not 0x01 but %02x. Format unknown, exiting."),
          *p);
        return 0; //fatal error
      }
      p++; //skip 0x01 byte
      unsigned short int l = ((*p << 8) | *(p + 1));
      u_char *p_end = p + l - 3; //this ensures a full block of 4 bytes is there to process
      p += 2; //skip length bytes
      while (p < p_end) {
        sSection0000BlockNagraGuide *S = (sSection0000BlockNagraGuide *) p;
        int TTT = ((S->TableIdExtensionHigh << 10) | (S->TableIdExtensionLow << 3) | (S->TIE200 << 9));
        LogD(4, prep("DEBUG: TableIdExtension %04x, Unknown1 %02x Version %02x Always 0xd6 %02x DayCounter %02x"),
             TTT, S->Unknown1, S->VersionNumber, S->Always0xd6, S->DayCounter);
        if ((TTT > 0x0400) && (TTT < 0x0600)) //take high byte and compare with summarie tables in 0x0400 and 0x0500 range;
          NagraTIE[NagraCounter++] = TTT; //only store TIEs of titlessummaries, all others can be derived; they are stored in the order of the 0x0000 index table,
        //lets hope first entry corresponds with today, next with tomorrow etc.
        p += 4;
      }
      buffer.clear (); //clear buffer maps
      bufsize.clear (); //clear buffer maps
      InitialTitle[0] = 0xff; //copy data into initial title
    }
    return (1);
  }
  unsigned short SectionLength = ((TBH->SectionLengthHigh & 0x0f) << 8) | TBH->SectionLengthLow;
  unsigned short TableIdExtension = HILO16 (TBH->TableIdExtension);
  if (TableIdExtension == 0x0000) {
    LastVersionNagra = Version;
    return (2); //done
  }
  /*
  Table_id_extensions:
  (0x0000)
  (0x0010) per channel, nr_of_channels entries, every entry is 8 bytes, first 4 bytes gives nr. of titles in corresponding title table
  (0x0020) per channel info day 2 of the month
  (0x01F0) per channel info day 31 of the month
  (0x0200) leeg; letop op je leest gemakkelijk door naar 0x0210!
  (0x0210) titles day 1 of the month
  (0x0220) titles day 2 of the month
  (0x03F0) titles day 31 of the month
  (0x0400) channel info
  (0x0410) summaries day 1 of the month
  (0x0420) summaries day 2 of the month
  (0x05F0) summaries day 31 of the month
  (0x0610) themes/title reference sunday, correspond to titles 0x0400 lower...
  (0x0620) themes/title reference monday
  ... this goes on until 0x07f0
  (0x0810) bouquet info; references to channels within a package, day 1 of the month
  (0x0820) same day 2 of the month
  (0x09f0) same day 31 of the month
   */

  if (!(TBH->TableIdExtensionHigh >= 0x02 && TBH->TableIdExtensionHigh <= 0x07)) //here we regulate which tables we are testing
    return (1);
  if (TableIdExtension == 0x0200) //table 0x0200 only contains language code, because it is for day 0 of the month, and 0x0400 is used for channels
    return 1;
  if (TBH->SectionNumber == 0) { //first section, create a table
    buffer[TableIdExtension] = NULL;
    bufsize[TableIdExtension] = 0;
    NumberOfTables++;
  }
  //store all sections in core until last section is found; processing incomplete sections is very complex and doesnt save much memory,
  //since the data has to be stored anyway; summaries do not seem to have channelid included, so storing titles and separately storing summaries will not work...
  //GetEventId only works for a specific Schedule for a specific ChannelId....
  buffer[TableIdExtension] =
    (unsigned char *) REALLOC (buffer[TableIdExtension], SectionLength - 9 + bufsize[TableIdExtension]);
  memcpy (buffer[TableIdExtension] + bufsize[TableIdExtension], Data + 8, SectionLength - 9); //append new section
  bufsize[TableIdExtension] += SectionLength - 9;
  if (TBH->SectionNumber >= TBH->LastSectionNumber) {
    LogI(1, prep("found %04x lastsection nr:%i."), TableIdExtension, TBH->SectionNumber);
    // if (TBH->TableIdExtensionHigh == 0x04 || TBH->TableIdExtensionHigh == 0x05) {
    if (TableIdExtension == 0x0400) {
      int Result = GetChannelsNagra (buffer[TableIdExtension] + 4, bufsize[TableIdExtension] - 4); //TODO language code terminated by 0 is ignored
      free (buffer[TableIdExtension]);
      buffer[TableIdExtension] = NULL;
      NumberOfTables--;
      if (Result == 0)
        return 0; //fatal error; TODO this exit should also free all other, non-Channel sections that are stored!
    }
  } //if lastsection read
  return (1); //return and continue, nonfatal
}

void cFilterEEPG::ProcessNagra ()
{
  for (int i = 0; i < MAX_THEMES; i++) //clear all themes
    Themes[i][0] = '\0';

  for (int i = 0; i < NagraCounter; i++) { //first prcoess all themes, since they all use the same codes
    unsigned short int TableIdExtension = NagraTIE[i];
    int TIE = TableIdExtension + 0x0200; //from 0x0400 to 0x0600 -> themes
    LogI(3, prep("Processing Theme with TableIdExtension:%04x"), TIE);
    GetThemesNagra (buffer[TIE] + 4, bufsize[TIE] - 4, TableIdExtension - 0x0200); //assume theme is completed  //TODO Language code terminatd by 0 is ignored
    free (buffer[TIE]);
    buffer[TIE] = NULL;
    NumberOfTables--;
  }

  for (int i = 0; i < NagraCounter; i++) { //first process all themes, since they all use the same codes
    unsigned short int TableIdExtension = NagraTIE[i];
    int TIE = TableIdExtension - 0x0200; //from 0x0400 to 0x0200 -> titles
    LogI(0, prep("Processing TableIdExtension:%04x"), TableIdExtension);
    GetTitlesNagra (buffer[TIE] + 4, bufsize[TIE] - 4, TableIdExtension); //assume title-reading is completed  //TODO Language code terminated by 0 is ignored
    free (buffer[TIE]);
    buffer[TIE] = NULL;
    NumberOfTables--;

    free (buffer[TableIdExtension]); //summaries
    buffer[TableIdExtension] = NULL;
    NumberOfTables--;
  }
  if (NumberOfTables != 0)
    LogE(0, prep("ERROR, Not all tables processed and stream is already repeating. NumberOfTables = %i."),
      NumberOfTables);
}

/**
 * \brief Get MHW1 Titles
 *
 * \return 0 = fatal error, code 1 = success, code 2 = last item processed
 */
int cFilterEEPG::GetTitlesMHW1 (const u_char * Data, int Length)
{
  if (Length >= 42) {
    sTitleMHW1 *Title = (sTitleMHW1 *) Data;
    if (Title->ChannelId == 0xff) { //FF is separator packet
      if (memcmp (InitialTitle, Data, 46) == 0) { //data is the same as initial title //TODO use easier notation
        LogD(2, prep("End processing titles"));
        return 2;
      }
      if (nTitles == 0)
        memcpy (InitialTitle, Data, 46); //copy data into initial title
      int Day = Title->Day;
      int Hours = Title->Hours;
      if (Hours > 15)
        Hours -= 4;
      else if (Hours > 7)
        Hours -= 2;
      else
        Day++;
      if (Day > 6)
        Day = Day - 7;
      Day -= Yesterday;
      if (Day < 1)
        Day = 7 + Day;
      //if (Day == 1 && Hours < 6)
      if (Day == 0 && Hours < 6)
        Day = 7;
      //Day = 8;
      MHWStartTime = (Day * 86400) + (Hours * 3600) + YesterdayEpochUTC;
      LogI(3, prep("Titles: FF PACKET, seqnr:%02x."), Data[5]);
    } else if (InitialTitle[0] != 0x00) { //if initialized this should always be 0x90 = tableid!
      if (nTitles < MAX_TITLES) {
        Title_t *T;
        T = (Title_t *) malloc (sizeof (Title_t));
        Titles[nTitles] = T;
        int Minutes = Title->Minutes;
        int StartTime = MHWStartTime + (Minutes * 60);
        T->ChannelId = Title->ChannelId - 1;
        T->ThemeId = Title->ThemeId;
        T->TableId = Title->TableId;
        T->MjdTime = 0;  //only used at MHW2 and SKY
        T->EventId = HILO32 (Title->ProgramId);
        T->StartTime = LocalTime2UTC (StartTime); //here also Daylight Savings correction is done
        T->Duration = HILO16 (Title->Duration) * 60;
        T->SummaryAvailable = Title->SummaryAvailable;
        T->Text = (unsigned char *) malloc (47);
        if (T->Text == NULL) {
          LogE(0, prep("Titles memory allocation error."));
          return 0;
        }
        //T->Text[46] = '\0'; //end string with NULL character
        //memcpy (T->Text, &Title->Title, 23);
        decodeText2((unsigned char *)&Title->Title, 23, (char*)T->Text, 47);
        CleanString (T->Text);
        LogI(3, prep("EvId:%08x,ChanId:%x, Titlenr:%d:, StartTime(epoch):%i, SummAv:%x,Name:%s."), T->EventId,
             T->ChannelId, nTitles, T->StartTime, T->SummaryAvailable, T->Text);
        nTitles++;
      } //nTitles < MaxTitles
      else {
        LogE(0, prep("Error, %i titles found more than %i"), nTitles, MAX_TITLES);
        return 0;
      }
    } //else if InitialTitle
  } //Length==46
  else {
    LogE(0, prep("Error, length of title package < 42."));
    return 1; //non fatal
  }

  return 1;
}

/**
 * \brief Get MHW2 Titles
 *
 * \return 0 = fatal error, code 1 = success, code 2 = last item processed
 */
int cFilterEEPG::GetTitlesMHW2 (const u_char * Data, int Length)
{
  if (Length > 18) {
    int Pos = 18;
    int Len = 0;
    /*bool Check = false;
    while (Pos < Length) {
      Check = false;
      Pos += 7;
      if (Pos < Length) {
        Pos += 3;
        if (Pos < Length)
          if (Data[Pos] > 0xc0) {
            Pos += (Data[Pos] - 0xc0);
            Pos += 4;
            if (Pos < Length) {
              if (Data[Pos] == 0xff) {
                Pos += 1;
                Check = true;
              }
            }
          }
      }
      if (Check == false){
        isyslog ("EEPGDebug: Check==false");
        return 1; // I assume nonfatal error or success
        }
    }*/
    if (memcmp (InitialTitle, Data, 16) == 0) { //data is the same as initial title
      return 2; //last item processed
    } else {
      if (nTitles == 0)
        memcpy (InitialTitle, Data, 16); //copy data into initial title
      //Pos = 18;
      while (Pos < Length) {
        Title_t *T;
        T = (Title_t *) malloc (sizeof (Title_t));
        Titles[nTitles] = T;
        T->ChannelId = Data[Pos];
        Pos+=11;//The date time starts here
        //isyslog ("EEPGDebug: ChannelID:%d", T->ChannelId);
        unsigned int MjdTime = (Data[Pos] << 8) | Data[Pos + 1];
        T->MjdTime = 0; //not used for matching MHW2
        T->StartTime = ((MjdTime - 40587) * 86400)
                       + (((((Data[Pos + 2] & 0xf0) >> 4) * 10) + (Data[Pos + 2] & 0x0f)) * 3600)
                       + (((((Data[Pos + 3] & 0xf0) >> 4) * 10) + (Data[Pos + 3] & 0x0f)) * 60);
        T->Duration = (((Data[Pos + 5] << 8) | Data[Pos + 6]) >> 4) * 60;
        Len = Data[Pos + 7] & 0x3f;
        //isyslog ("EEPGDebug: Len:%d", Len);
        T->Text = (unsigned char *) malloc (2 * Len + 1);
        if (T->Text == NULL) {
          LogE(0, prep("Titles memory allocation error."));
          return 0; //fatal error
        }
        decodeText2(&Data[Pos + 8],Len,(char*)T->Text,2 * Len + 1);
        //T->Text[Len] = '\0'; //end string with NULL character
        //memcpy (T->Text, &Data[Pos + 8], Len);
        CleanString (T->Text);
        Pos += Len + 8; // Sub Theme starts here
        T->ThemeId = ((Data[7] & 0x3f) << 6) | (Data[Pos] & 0x3f);
        T->TableId = DEFAULT_TABLE_ID; //TODO locate the actual table id
        T->EventId = (Data[Pos + 1] << 8) | Data[Pos + 2];
        T->SummaryAvailable = (T->EventId != 0xFFFF);
        LogI(3, prep("EventId %04x Titlenr %d:SummAv:%x,Name:%s."), T->EventId,
             nTitles, T->SummaryAvailable, T->Text);
        Pos += 3;
        nTitles++;
        if (nTitles > MAX_TITLES) {
          LogE(0, prep("Error, %i titles found more than %i"), nTitles, MAX_TITLES);
          return 0; //fatal error
        }
      }
      return 1; //success
    } //else memcmp
  } //if length
  return 1; //non fatal error
}

/**
 * \brief Get MHW1 Summaries
 *
 * \return 0 = fatal error, code 1 = success, code 2 = last item processed
 */
int cFilterEEPG::GetSummariesMHW1 (const u_char * Data, int Length)
{
  sSummaryMHW1 *Summary = (sSummaryMHW1 *) Data;
  if (Length >= 11) {
    if (Summary->NumReplays < 10) { //Why limit this at 10?
      if (Length >= (11 + (Summary->NumReplays * 7))) {
        if (Summary->Byte7 == 0xff && Summary->Byte8 == 0xff && Summary->Byte9 == 0xff) {
          if (memcmp (InitialSummary, Data, 20) == 0) { //data is equal to initial buffer
            return 2;
          } else if (nSummaries < MAX_TITLES) {
            if (nSummaries == 0)
              memcpy (InitialSummary, Data, 20); //copy this data in initial buffer
            int SummaryOffset = 11 + (Summary->NumReplays * 7);
            int SummaryLength = Length - SummaryOffset;
            unsigned char *Text = (unsigned char *) malloc (2*SummaryLength + 1);
            if (Text == NULL) {
              LogE(0, prep("Summaries memory allocation error."));
              return 0;
            }
            Text[SummaryLength+1] = '\0'; //end string with NULL character
            //memcpy (Text, &Data[SummaryOffset], SummaryLength);
            decodeText2(&Data[SummaryOffset], SummaryLength, (char*)Text, 2*SummaryLength + 1);
//     CleanString (Text);
//          if (Summary->NumReplays != 0)
//          esyslog ("EEPG: Number of replays:%i.", Summary->NumReplays);
            //int Replays = Summary->NumReplays;
            int ReplayOffset = 11;
            Summary_t *S;
            S = (Summary_t *) malloc (sizeof (Summary_t));
            Summaries[nSummaries] = S;
            S->NumReplays = Summary->NumReplays;
            S->EventId = HILO32 (Summary->ProgramId);
            S->Text = Text;
            S->ShortTextLength = 0; //TODO find for MHW1
            int i = 0;
            do {
              S->Replays[i].MjdTime = 0; //only used for SKY
              //if (Summary->NumReplays == 0) {
              //S->ChannelId = 0xFFFF; //signal that ChannelId is not known; 0 is bad signal value because it is a valid ChannelId...
              //S->StartTime = 0;
              //}
              //else {
              S->Replays[i].ChannelId = Data[ReplayOffset++] - 1;
              unsigned int Date_hi = Data[ReplayOffset++];
              unsigned int Date_lo = Data[ReplayOffset++];
              unsigned short int Hour = Data[ReplayOffset++];
              unsigned short int Minute = Data[ReplayOffset++];
              unsigned short int Sec = Data[ReplayOffset++];
              ReplayOffset++; //makes total of 7 bytes

              LogI(4, prep("EvId:%08x ChanId:%x, ChanName %s, Time: %02d:%02d:%02d."),
                   S->EventId, S->Replays[i].ChannelId,
                   sChannels[ChannelSeq[S->Replays[i].ChannelId]].Name, Hour, Minute, Sec);

              S->Replays[i].StartTime = MjdToEpochTime (Date) + (((((Hour & 0xf0) >> 4) * 10) + (Hour & 0x0f)) * 3600)
                                        + (((((Minute & 0xf0) >> 4) * 10) + (Minute & 0x0f)) * 60)
                                        + ((((Sec & 0xf0) >> 4) * 10) + (Sec & 0x0f));
//       summary -> time[i] = ProviderLocalTime2UTC (summary -> time[i]);
              S->Replays[i].StartTime = LocalTime2UTC (S->Replays[i].StartTime);
              //}
              i++;
            } while (i < Summary->NumReplays);
            //} while (Replays-- >= 0);
            LogI(3, prep("EvId:%08x ChanId:%x, Replays:%d, Summnr %d:%.35s."), S->EventId,
                 S->Replays[0].ChannelId, S->NumReplays, nSummaries, S->Text);
            nSummaries++;
          } else {
            LogE(0, prep("Error, %i summaries found more than %i"), nSummaries, MAX_TITLES);
            return 0;
          }
        } //0xff
        else {
          LogE(0, prep("Warning, Summary bytes not as expected."));
          return 1; //it is not a success, but error is not fatal
        }
      } //numreplays length
      else {
        LogE(0, prep("Warning, number of replays is not conforming to length."));
        return 1; //nonfatal error
      }
    } //numreplays <10
    else {
      LogE(0, prep("Warning, number of replays %d > 10, cannot process."),
        Summary->NumReplays);
      return 1; //nonfatal error
    }
  } //length >11
  else {
    LogE(0, prep("Summary length too small:%s"), cs_hexdump (0, Data, Length));
    return 1; //nonfatal error
  }
  return 1; //success
}

/**
 * \brief Get MHW2 Summaries
 *
 * \return 0 = fatal error, code 1 = success, code 2 = last item processed
 */
int cFilterEEPG::GetSummariesMHW2 (const u_char * Data, int Length)
{
  if (Length > (Data[14] + 17)) {
    if (memcmp (InitialSummary, Data, 16) == 0) //data is equal to initial buffer
      return 2;
    else {
      if (nSummaries == 0)
        memcpy (InitialSummary, Data, 16); //copy this data in initial buffer
      if (nSummaries < MAX_TITLES) {
        int lenText = Data[14];
        int SummaryLength = lenText;
        int Pos = 15;
        int Loop = Data[Pos + SummaryLength] & 0x0f;
        Summary_t *S;
        S = (Summary_t *) malloc (sizeof (Summary_t));
        Summaries[nSummaries] = S;

        S->Replays[0].ChannelId = 0xFFFF; //signal that ChannelId is not known; 0 is bad signal value because it is a valid ChannelId...
        S->Replays[0].StartTime = 0; //not used
        S->Replays[0].MjdTime = 0;  //not used
        S->NumReplays = 0; //not used
        S->EventId = (Data[3] << 8) | Data[4];
        unsigned char tmp[4096]; //TODO do this smarter
        memcpy (tmp, &Data[Pos], lenText);
        tmp[SummaryLength] = '\n';
        SummaryLength += 1;
        Pos += (lenText + 1);
        if (Loop > 0) {
          while (Loop > 0) {
            lenText = Data[Pos];
            Pos += 1;
            if ((Pos + lenText) < Length) {
              memcpy (&tmp[SummaryLength], &Data[Pos], lenText);
              SummaryLength += lenText;
              if (Loop > 1) {
                tmp[SummaryLength] = ' ';// This is considered as an EPG bug in VDR '\n';
                SummaryLength += 1;
              }
            } else
              break;
            Pos += lenText;
            Loop--;
          }
        }
        S->Text = (unsigned char *) malloc (2 * SummaryLength + 1);
        if (S->Text == NULL) {
          LogE(0, prep("Summaries memory allocation error."));
          return 0; //fatal error
        }
        //memcpy (S->Text, tmp, SummaryLength);
        //S->Text[SummaryLength] = '\0'; //end string with NULL character
        decodeText2(tmp,SummaryLength,(char*)S->Text,2 * SummaryLength + 1);
        CleanString (S->Text);
        char * delim = strchr ( (char *)S->Text, '\n' );
        S->ShortTextLength = delim == NULL ? 0 : delim - (char *)S->Text;

        LogI(3, prep("EventId %08x Summnr %d:%.30s."), S->EventId, nSummaries, S->Text);
        nSummaries++;
      } else {
        LogE(0, prep("Error, %i summaries found more than %i"), nSummaries, MAX_TITLES);
        return 0; //fatal error
      }
    } //else
  } //if length
  return 1; //succes or nonfatal error
}

/**
 * \brief Get SKYBOX Channels
 *
 * \return 0 = fatal error, code 1 = success, code 2 = last item processed
 */
int cFilterEEPG::GetChannelsSKYBOX (const u_char * Data, int Length)
{

  if (memcmp (InitialChannel, Data, 8) == 0) { //data is the same as initial title
    //LoadEquivalentChannels ();
      EquivHandler->loadEquivalentChannelMap();
    return 2;
  } else {
    if (nChannels == 0)
      memcpy (InitialChannel, Data, 8); //copy data into initial title
    if (nChannels == 0) {
      LogI(1, "|  ID  | %-26.26s | %-22.22s | FND | %-8.8s |\n", "Channel ID", "Channel Name", "Sky Num.");
      LogI(1, "|------|-%-26.26s-|-%-22.22s-|-----|-%-8.8s-|\n", "------------------------------",
           "-----------------------------", "--------------------");
    }
//    unsigned short int BouquetId = (Data[3] << 8) | Data[4];
    int BouquetDescriptorsLength = ((Data[8] & 0x0f) << 8) | Data[9];
    int TransportStreamLoopLength =
      ((Data[BouquetDescriptorsLength + 10] & 0x0f) << 8) | Data[BouquetDescriptorsLength + 11];
    int p1 = (BouquetDescriptorsLength + 12);
    while (TransportStreamLoopLength > 0) {
      unsigned short int Tid = (Data[p1] << 8) | Data[p1 + 1];
      unsigned short int Nid = (Data[p1 + 2] << 8) | Data[p1 + 3];
      int TransportDescriptorsLength = ((Data[p1 + 4] & 0x0f) << 8) | Data[p1 + 5];
      int p2 = (p1 + 6);
      p1 += (TransportDescriptorsLength + 6);
      TransportStreamLoopLength -= (TransportDescriptorsLength + 6);
      while (TransportDescriptorsLength > 0) {
        unsigned char DescriptorTag = Data[p2];
        int DescriptorLength = Data[p2 + 1];
        int p3 = (p2 + 2);
        p2 += (DescriptorLength + 2);
        TransportDescriptorsLength -= (DescriptorLength + 2);
        switch (DescriptorTag) { //TODO switch with only 1 case??? replace this by template
        case 0xb1:
          p3 += 2;
          DescriptorLength -= 2;
          while (DescriptorLength > 0) {
            // 0x01 = Video Channel
            // 0x02 = Audio Channel
            // 0x05 = Other Channel
            //if( Data[p3+2] == 0x01 || Data[p3+2] == 0x02 || Data[p3+2] == 0x05 )
            //{
            unsigned short int Sid = (Data[p3] << 8) | Data[p3 + 1];
            unsigned short int ChannelId = (Data[p3 + 3] << 8) | Data[p3 + 4];
            unsigned short int SkyNumber = (Data[p3 + 5] << 8) | Data[p3 + 6];
            if (SkyNumber > 100 && SkyNumber < 1000) {
              if (ChannelId > 0) {
                sChannel *C;
                if (ChannelSeq.count (ChannelId) == 0) { //not found
                  C = &sChannels[nChannels];
                  C->ChannelId = ChannelId;
                  //C->NumberOfEquivalences = 1; //there is always an original channel. every equivalence adds 1
                  C->Src = Source (); //assume all EPG channels are on same satellite, if not, manage this via equivalents!!!
                  C->Nid = Nid;
                  C->Tid = Tid;
                  C->Sid = Sid;
                  C->SkyNumber = SkyNumber;
                  tChannelID channelID = tChannelID (C->Src, C->Nid, C->Tid, C->Sid);
                  cChannel *VC = Channels.GetByChannelID (channelID, true);
                  bool IsFound = (VC);
                  if (IsFound)
                    strncpy ((char *) C->Name, VC->Name (), 64);
                  else
                    C->Name[0] = '\0'; //empty string

                  LogI(1, "|% 5d | %-26.26s | %-22.22s | %-3.3s |  % 6d  |\n", C->ChannelId
                       , *channelID.ToString(), C->Name, IsFound ? "YES" : "NO", C->SkyNumber);

                  ChannelSeq[C->ChannelId] = nChannels; //fill lookup table to go from channel-id to sequence nr in table
                  nChannels++;
                  if (nChannels >= MAX_CHANNELS) {
                    LogE(0, prep("Error, %i channels found more than %i"), nChannels, MAX_CHANNELS);
                    return 0;
                  }
                }
              }
            }
            p3 += 9;
            DescriptorLength -= 9;
          }
          break;
        default:
          break;
        } //switch descriptortag
      }
    } //while
    return 1;
  } //else part of memcmp
}

/**
 * \brief Get SKYBOX Titles
 *
 * \return 0 = fatal error, code 1 = success, code 2 = last item processed
 */
int cFilterEEPG::GetTitlesSKYBOX (const u_char * Data, int Length)
{
  int p;
  unsigned short int ChannelId;
  unsigned short int MjdTime;
  int Len1;
  int Len2;

  if (Length < 20)
    return 1; //nonfatal error
  if (memcmp (InitialTitle, Data, 20) == 0) //data is the same as initial title
    return 2;
  else {
    if (nTitles == 0)
      memcpy (InitialTitle, Data, 20); //copy data into initial title
    ChannelId = (Data[3] << 8) | Data[4];
    MjdTime = ((Data[8] << 8) | Data[9]);
    if (ChannelId > 0) {
      if (MjdTime > 0) {
        p = 10;
        do {
          Title_t *T;
          T = (Title_t *) malloc (sizeof (Title_t));
          Titles[nTitles] = T;
          T->ChannelId = ChannelId;
          T->MjdTime = MjdTime; //only date, no time. Is used to match titles and summaries, SKYBOX only
          T->EventId = (Data[p] << 8) | Data[p + 1];
          Len1 = ((Data[p + 2] & 0x0f) << 8) | Data[p + 3];
          if (Data[p + 4] != 0xb5) {
            LogD(5, prep("Data error signature for title - Data[p + 4] != 0xb5"));
            break;
          }
          if (Len1 > Length) {
            LogD(5, prep("Data error signature for title - Len1 > Length"));
            break;
          }
          p += 4;
          Len2 = Data[p + 1] - 7;
          T->StartTime = ((MjdTime - 40587) * 86400) + ((Data[p + 2] << 9) | (Data[p + 3] << 1));
          T->Duration = ((Data[p + 4] << 9) | (Data[p + 5] << 1));
          T->ThemeId = Data[p + 6];
          T->TableId = DEFAULT_TABLE_ID; //TODO locate the actual table id
          //TODO Data[p + 7] is Quality value add it to description
          //int quality = Data[p + 7];
          switch (Data[p + 8] & 0x0F) {
          case 0x01:
            T->Rating = 0x00; //"U"
            break;
          case 0x02:
            T->Rating = 0x08; //"PG"
            break;
          case 0x03:
            T->Rating = 0x0C; //"12"
            break;
          case 0x04:
            T->Rating = 0x0F; //"15"
            break;
          case 0x05:
            T->Rating = 0x12; //"18"
            break;
          default:
            T->Rating = 0x00; //"-"
            break;
          }
          T->Unknown1 = Data[p + 4 - 13]; //FIXME
          T->Unknown2 = Data[p + 4 - 12]; //FIXME
          T->Unknown3 = Data[p + 4 - 11]; //FIXME
          unsigned char tmp[4096]; //TODO smarter
          Len2 = sky_huffman_decode (&Data[p + 9], Len2, tmp);
          if (Len2 == 0) {
            LogE(0, prep("Warning, could not huffman-decode title-text, skipping title."));
            return 1; //non-fatal error
          }
          T->Text = (unsigned char *) malloc (Len2 + 1);
          if (T->Text == NULL) {
            LogE(0, prep("Titles memory allocation error."));
            return 0;
          }
          T->Text[Len2] = '\0'; //end string with NULL character
          memcpy (T->Text, tmp, Len2);
          CleanString (T->Text);
          T->SummaryAvailable = 1; //TODO I assume this is true?

          LogI(3, prep("EventId %08x Titlenr %d,Unknown1:%x,Unknown2:%x,Un3:%x,Name:%s."),
               T->EventId, nTitles, T->Unknown1, T->Unknown2, T->Unknown3, T->Text);

          p += Len1;
          nTitles++;
          if (nTitles >= MAX_TITLES) {
            LogE(0, prep("Error, %i titles found more than %i"), nTitles, MAX_TITLES);
            return 0; //fatal error
          }
        } while (p < Length);
      }
    }
  }
  return 1; //success
}

/**
 * \brief Get SKYBOX Summaries
 *
 * \return 0 = fatal error, code 1 = success, code 2 = last item processed
 */
int cFilterEEPG::GetSummariesSKYBOX (const u_char * Data, int Length)
{
  int p;
  unsigned short int ChannelId;
  unsigned short int MjdTime;
  int Len1;
  int Len2;
  const char* STxtDelim = Format == SKY_UK?": ":" - ";

  if (Length < 20) {
    return 1; //non fatal error I assume
  }
  if (memcmp (InitialSummary, Data, 20) == 0) //data is equal to initial buffer
    return 2;
//        else if (nSummaries < MAX_SUMMARIES) {
  else {
    if (nSummaries == 0)
      memcpy (InitialSummary, Data, 20); //copy this data in initial buffer
    ChannelId = (Data[3] << 8) | Data[4];
    MjdTime = ((Data[8] << 8) | Data[9]);
    if (ChannelId > 0) {
      if (MjdTime > 0) {
        p = 10;
        do {
          Summary_t *S;
          S = (Summary_t *) malloc (sizeof (Summary_t));
          Summaries[nSummaries] = S;
          S->Replays[0].ChannelId = ChannelId;
          S->Replays[0].MjdTime = MjdTime;
          S->NumReplays = 0; //not used
          S->EventId = (Data[p] << 8) | Data[p + 1];
          S->ShortTextLength = 0;
          Len1 = ((Data[p + 2] & 0x0f) << 8) | Data[p + 3];
          if (Data[p + 4] != 0xb9) {
            LogD(5, prep("Data error signature for title - Data[p + 4] != 0xb5"));
            break;
          }
          if (Len1 > Length) {
            LogD(5, prep("Data error signature for title - Len1 > Length"));
            break;
          }
          p += 4;
          Len2 = Data[p + 1];
          unsigned char tmp[4096]; //TODO can this be done better?
          Len2 = sky_huffman_decode (&Data[p + 2], Len2, tmp);
          if (Len2 == 0) {
            LogE(0, prep("Warning, could not huffman-decode text, skipping summary."));
            return 1; //non-fatal error
          }
          S->Text = (unsigned char *) malloc (Len2 + 1);
          if (S->Text == NULL) {
            LogE(0, prep("Summaries memory allocation error."));
            return 0;
          }
          memcpy (S->Text, tmp, Len2);
          S->Text[Len2] = '\0'; //end string with NULL character
          CleanString (S->Text);
          char * delim = strstr ( (char *)S->Text, STxtDelim );
          S->ShortTextLength = delim == NULL ? 0 : delim - (char *)S->Text;
          LogI(3, prep("EventId %08x Summnr %d:%.30s."), S->EventId, nSummaries, S->Text);
          p += Len1;
          nSummaries++;
          if (nSummaries >= MAX_TITLES) {
            LogI(0, prep("Error, %i summaries found more than %i"), nSummaries, MAX_TITLES);
            return 0;
          }
        } while (p < Length);
      }
    }
  }
  return 1;
}

void cFilterEEPG::FreeSummaries (void)
{
  if (Format == MHW1 || Format == MHW2 || Format == SKY_IT || Format == SKY_UK) {
    Summary_t *S; //TODO do I need this?
    Summary_t *S2; //TODO do I need this?
    for (int i = 0; i < nSummaries; i++) {
      S = Summaries[i];
      if (i < nSummaries - 1) {
        S2 = Summaries[i + 1]; //look at next summary
        if (S->Text != S2->Text && S->Text != 0x00) //this is the last summary that points to this text block; needed in case NumReplays > 1, multiple pointers to same textblock
          free (S->Text);
      } else if (S->Text != 0x00)
        free (S->Text);
      free (S);
    }
  }
  nSummaries = 0;
}

void cFilterEEPG::FreeTitles (void)
{
  if (Format == MHW1 || Format == MHW2 || Format == SKY_IT || Format == SKY_UK) {
    Title_t *T;
    for (int i = 0; i < nTitles; i++) {
      T = Titles[i];
      free (T->Text);
      free (T);
    }
  }
  nTitles = 0;
}

void cFilterEEPG::LoadIntoSchedule (void)
{
  int i, j;
  i = 0;
  j = 0;
  bool foundtitle;
  foundtitle = false;
  Title_t *T;
  Summary_t *S;
  int remembersummary;
  //keep statistics
  int SummariesNotFound = 0;
  int NoSummary = 0;
  int NotMatching = 0;
  int LostSync = 0;
  remembersummary = -1;

  {
  cSchedulesLock SchedulesLock (true);
  cSchedules *s = (cSchedules *) cSchedules::Schedules (SchedulesLock);
  if (s) {

    while (i < nTitles) {
      T = Titles[i];
      S = Summaries[j];
      foundtitle = false;

      while ((i < nTitles) && (!foundtitle)) { //find next title that has summary
        T = Titles[i];
        if (T->SummaryAvailable)
          foundtitle = true;
        else {
          NoSummary++;
          i++;
        }
      }
//esyslog("foundtitle %x for next title that has a summary:%d",foundtitle,i);

      if (!foundtitle)  //no more titles with summaries
        break;
      if ((T->EventId == S->EventId) && (T->MjdTime == S->Replays[0].MjdTime)
        && ((T->ChannelId == S->Replays[0].ChannelId) || ((Format != SKY_IT) && (Format != SKY_UK)))) { //should always be true, titles and summaries are broadcasted in order...
        LogD(3, prep("T->EventId == S->EventId"));
        //MjdTime = 0 for all but SKY
        //S->ChannelId must be equal to T->ChannelId only for SKY; in MHW1 S->ChannelId overrides T->ChannelId when NumReplays > 1
        remembersummary = -1; //reset summary searcher
        //int Replays = S->NumReplays;

        int index = 0;
        do {
          unsigned short int ChannelId;
          time_t StartTime;
          if (S->NumReplays == 0) {
            ChannelId = T->ChannelId;
            StartTime = T->StartTime;
          } else {
            ChannelId = S->Replays[index].ChannelId;
            StartTime = S->Replays[index].StartTime;
          }

          //channelids are sequentially numbered and sent in MHW1 and MHW2, but not in SKY, so we need to lookup the table index
          sChannel *C = &sChannels[ChannelSeq[ChannelId]]; //find channel
          //cSchedule *p;//[MAX_EQUIVALENCES];
          //PrepareToWriteToSchedule (C, s, p);
          tChannelID chanID = tChannelID (C->Src, C->Nid, C->Tid, C->Sid);

          char rating = 0x00;
          if ((Format == SKY_IT || Format == SKY_UK) &&  T->Rating) { //TODO only works on OTV for now
            rating = T->Rating;
          }
          unsigned short int TableId = DEFAULT_TABLE_ID;
          if (T->TableId) {
            TableId = T->TableId;
          }

//          LogD (0, prep("EventId %08x Titlenr %d:SummAv:%x,Un1:%x,Un2:%x,Un3:%x,Name:%s,STxtLn:%dSummary:%s."),
//                      T->EventId, i, T->SummaryAvailable, T->Unknown1, T->Unknown2, T->Unknown3, T->Text, S->ShortTextLength, S->Text);

          WriteToSchedule (chanID, s, T->EventId, StartTime, T->Duration / 60, (char *) T->Text,
                           (char *) S->Text, T->ThemeId, TableId, 0, rating, S->ShortTextLength);
          sortSchedules(s, chanID);
          //if (shortText != NULL) delete [] shortText;

          //FinishWriteToSchedule (C, s, p);
          //Replays--;
          //if ((S->NumReplays != 0) && (Replays > 0)) { //when replays are used, all summaries of the replays are stored consecutively; currently only CSAT
          //j++;  //move to next summary
          //if (j >= nSummaries) //do not forget to look in beginning of (ring)buffer
          //j = 0;
          //S = Summaries[j]; //next summary within replay range
          //}
          index++;
        }   //while
        while (index < S->NumReplays);

        //TODO: why load events that have already past, and then run Cleanup
        //end of putting title and summary in schedule
        i++; //move to next title
      }    //if T->EventId == S->EventId
      else {
//      esyslog("EEPG ERROR: ProgramIds not matching, title:%d,summary%d, T->EventId:%u, S->Eventid:%u.",i,j,T->EventId,S->EventId);
        NotMatching++;
        if (remembersummary == -1) { //I am not in search loop yet
          remembersummary = j;
          if (remembersummary == 0)
            remembersummary = nSummaries; //or next test will never be succesfull for remembersummary = 0
          LostSync++;
//      esyslog("EEPG Error: lost sync at title %d, summary %d.",i,j);
        } else if (j == (remembersummary - 1)) { //the last summary to be checked has failed also
          //esyslog ("EEPG Error: could not find summary for summary-available Title %d.", i);
          esyslog
          ("EEPG: Error, summary not found for EventId %08x Titlenr %d:SummAv:%x,Unknown1:%x,Unknown2:%x,Un3:%x,Name:%s.",
            T->EventId, i, T->SummaryAvailable, T->Unknown1, T->Unknown2, T->Unknown3, T->Text);

          /* write Title info to schedule */
          sChannel *C = &sChannels[ChannelSeq[T->ChannelId]]; //find channel
          //cSchedule *p;//[MAX_EQUIVALENCES];
          tChannelID chanID = tChannelID (C->Src, C->Nid, C->Tid, C->Sid);
          //PrepareToWriteToSchedule (C, s, p);
          char rating = 0x00;
          if ((Format == SKY_IT || Format == SKY_UK) &&  T->Rating) { //TODO only works on OTV for now
            rating = T->Rating;
          }
          WriteToSchedule (chanID, s, T->EventId, T->StartTime, T->Duration / 60, (char *) T->Text,
                           NULL, T->ThemeId, DEFAULT_TABLE_ID, 0, rating, S->ShortTextLength);
          //FinishWriteToSchedule (C, s, p);
          sortSchedules(s, chanID);

          SummariesNotFound++;
          i++; //move to next title, for this one no summary can be found
        }

//      esyslog("Trying again for this title %d, remember summary %d, but advancing one Summary to %d.",i,remembersummary,j);
      }
      j++; //move to next summary
      if (j >= nSummaries) //do not forget to look in beginning of (ring)buffer
        j = 0;
    } //while title
  } // if s
  else
    LogE (0, prep("Error: could not lock schedules."));

  }//release ScheduleLock
  cSchedules::Cleanup (true); //deletes all past events

  //isyslog ("EEPG: found %i equivalents channels", nEquivChannels);
  isyslog ("EEPG: found %i themes", nThemes);
  isyslog ("EEPG: found %i channels", nChannels);
  isyslog ("EEPG: found %i titles", nTitles);
  if (NoSummary != 0)
    isyslog ("EEPG: of which %i reported to have no summary available; skipping these BIENTOT titles", NoSummary);
  isyslog ("EEPG: found %i summaries", nSummaries);
  if (SummariesNotFound != 0)
    esyslog ("EEPG: %i summaries not found", SummariesNotFound);
  if (NotMatching > nSummaries)
    LogI (0, prep("Warning: lost sync %i times, summary did not match %i times."),
      LostSync, NotMatching);

  FreeSummaries (); //do NOT free channels, themes and bouquets here because they will be reused in SKY!
  FreeTitles ();
  if (!((Format == SKY_IT) || (Format == SKY_UK))) { //everything but SKY; SKY is the only protocol where LoadIntoSchedule is called repeatedly
    ChannelSeq.clear ();
  }
}

void cFilterEEPG::AddFilter (u_short Pid, u_char Tid)
{
  if (!Matches (Pid, Tid)) {
    Add (Pid, Tid);
    esyslog (prep("Filter Pid:%x,Tid:%x added."), Pid, Tid);
  }
}

void cFilterEEPG::AddFilter (u_short Pid, u_char Tid, unsigned char Mask)
{
  if (!Matches (Pid, Tid)) {
    Add (Pid, Tid, Mask);
    esyslog (prep("Filter Pid:%x,Tid:%x,Mask:%x added."), Pid, Tid, Mask);
  }
}

void cFilterEEPG::ProcessNextFormat (bool FirstTime = false)
{
  /*  for (int i = 0; i <= HIGHEST_FORMAT; i++)
      esyslog ("EEPGDEBUG: Format %i on pid %x", i, UnprocessedFormat[i]); */

  if (!FirstTime) {
    //isyslog ("EEPG: found %i equivalents channels", equiChanMap.size());
    isyslog ("EEPG: found %i themes", nThemes);
    isyslog ("EEPG: found %i channels", nChannels);
    isyslog ("EEPG: found %i titles", nTitles);
    isyslog ("EEPG: found %i summaries", nSummaries);
    isyslog ("EEPG: written %i titles", TitleCounter);
    isyslog ("EEPG: written %i summaries", SummaryCounter);
    isyslog ("EEPG: rejected %i titles/summaries because of higher TableId", RejectTableId);
    //Send message when finished
    if (SetupPE->DisplayMessage) {
      char *mesg;
      Asprintf(&mesg, "EEPG: written %i summaries", SummaryCounter);
      Skins.QueueMessage(mtInfo, mesg, 2);
      free(mesg);
    }

    TitleCounter = 0;
    SummaryCounter = 0;
    /*if (SummariesNotFound != 0)
       esyslog ("EEPG: %i summaries not found", SummariesNotFound);
       else if (VERBOSE >= 1)
       isyslog ("EEPG: %i summaries not found", SummariesNotFound); */
    UnprocessedFormat[Format] = 0; //clear previously processed format

    //Next few lines prevent eepg from reading multiple eepg-systems on one transponder e.g. CDNL
    //isyslog ("EEPG: Ended all processing");
    //return;
    //If you remove these lines, multiple systems WILL be read

  }
  TitleCounter = 0;
  SummaryCounter = 0;
  RejectTableId = 0;
  //cleanup mess of last processing
  ChannelSeq.clear ();
  FreeTitles ();
  FreeSummaries ();

  // Enable EIT scan for all except DISH_BEV since it is already enabled
  if (SetupPE->ProcessEIT && !UnprocessedFormat[EIT]
     && !UnprocessedFormat[FREEVIEW] && !UnprocessedFormat[DISH_BEV]) {
    UnprocessedFormat[EIT] = EIT_PID;
    EquivHandler->loadEquivalentChannelMap();
  }

  //now start looking for next format to process
  int pid;
  for (int i = 0; i <= HIGHEST_FORMAT; i++){ //find first format that is detected
    if (UnprocessedFormat[i]) {
      isyslog ("EEPG: %s Extended EPG detected on pid %x.", FormatName[i], UnprocessedFormat[i]);
      Format = (EFormat)i;
      // highest format is processed first this way
      // make sure that CONT protocols like Premiere, Freesat are processed
      // AFTER ONCE protocols like MHW, SKY and NAGRA
      break;
    }
    if (i == HIGHEST_FORMAT) { //there are no formats left to process
      isyslog ("EEPG: Ended all processing");
      return;
    }
  }

  pid = UnprocessedFormat[Format]; //and reinstall its pid

  memset (&InitialChannel, 0, 8);
  memset (&InitialTitle, 0, 64);
  memset (&InitialSummary, 0, 64);
  NagraCounter = 0;
  Version = -1; //because 0 can be a valid version number...
  nChannels = 0;
  nThemes = 0;
  EndChannels = false;
  EndThemes = false;
  switch (Format) {
  case PREMIERE:
    AddFilter (pid, 0xA0);
    break;
  case MHW1:
    AddFilter (0xd3, 0x92); //ThemesMHW1//TODO: all filters are serialized, strictly speaking Themes is non-fatal...
    break;
  case MHW2:
    AddFilter (0x231, 0xc8); //MHW2 Channels & Themes
    break;
  case SKY_IT:
  case SKY_UK:
    AddFilter (0x11, 0x4a); //Sky Channels
    break;
  case FREEVIEW: //Freeview, CONT mode //TODO streamline this for other modes
    InitDictionary ();
    AddFilter (pid, 0x4e, 0xfe); //event info, actual(0x4e)/other(0x4f) TS, present/following
    AddFilter (pid, 0x50, 0xf0); //event info, actual TS, schedule(0x50)/schedule for future days(0x5X)
    AddFilter (pid, 0x60, 0xf0); //event info, other  TS, schedule(0x60)/schedule for future days(0x6X)
    AddFilter (0x39, 0x50, 0xf0); //event info, actual TS, Viasat
    AddFilter (0x39, 0x60, 0xf0); //event info, other  TS, Viasat
    break;
  case NAGRA:
    AddFilter (pid, 0xb0); //perhaps TID is equal to first data byte?
    break;
  case DISH_BEV:
#if APIVERSNUM < 10726
    AddFilter (EIT_PID, 0, 0); // event info, actual(0x4e)/other(0x4f) TS, present/following
#endif
    AddFilter (0x0300, 0, 0); // Dish Network EEPG event info, actual(0x4e)/other(0x4f) TS, present/following
    AddFilter (0x0441, 0, 0); // Dish Network EEPG event info, actual(0x4e)/other(0x4f) TS, present/following
//    AddFilter (0x0441, 0x50, 0xf0); // Bell ExpressVU EEPG
//    AddFilter (0x0441, 0x60, 0xf0); // Bell ExpressVU EEPG
    break;
  case EIT:
    AddFilter (pid, 0x4e, 0xfe); //event info, actual(0x4e)/other(0x4f) TS, present/following
    AddFilter (pid, 0x50, 0xf0); //event info, actual TS, schedule(0x50)/schedule for future days(0x5X)
    AddFilter (pid, 0x60, 0xf0); //event info, other  TS, schedule(0x60)/schedule for future days(0x6X)
    break;
  default:
    break;
  }
}

void cFilterEEPG::ProccessContinuous(u_short Pid, u_char Tid, int Length, const u_char *Data)
{
  //0x39 Viasat, 0x0300 Dish Network EEPG, 0x0441 Bell ExpressVU EEPG
  LogD(4, prep("Pid: 0x%02x Tid: %d Length: %d"), Pid, Tid, Length);
  cSchedulesLock SchedulesLock(true, 10);
  cSchedules *Schedules = (cSchedules*)(cSchedules::Schedules(SchedulesLock));
  //Look for other satelite positions only if Dish/Bell ExpressVU for the moment hardcoded pid check
  if(Schedules)
    SI::cEIT2 EIT(Schedules, Source(), Tid, Data, Pid == EIT_PID);

  else//cEIT EIT (Schedules, Source (), Tid, Data);
  {
    // If we don't get a write lock, let's at least get a read lock, so
    // that we can set the running status and 'seen' timestamp (well, actually
    // with a read lock we shouldn't be doing that, but it's only integers that
    // get changed, so it should be ok)
    cSchedulesLock SchedulesLock;
    cSchedules *Schedules = (cSchedules*)(cSchedules::Schedules(SchedulesLock));
    if(Schedules)
      SI::cEIT2 EIT(Schedules, Source(), Tid, Data, Pid == EIT_PID, true);

    //cEIT EIT (Schedules, Source (), Tid, Data, true);
  }
}

void cFilterEEPG::Process (u_short Pid, u_char Tid, const u_char * Data, int Length)
{
  int now = time (0);
//  LogD(2, prep("Pid: 0x%02x Tid: %d Length: %d PMT pid: 0x%04x"), Pid, Tid, Length, pmtpid);
//  LogD(2, prep("Source: %d Transponder: %d"), Source () , Transponder ());

  if (Pid == 0 && Tid == SI::TableIdPAT) {
    if (!pmtnext || now > pmtnext) {
      if (pmtpid)
        NextPmt ();
      if (!pmtpid) {
        SI::PAT pat (Data, false);
        if (pat.CheckCRCAndParse ()) {
          SI::PAT::Association assoc;
          int idx = 0;
          for (SI::Loop::Iterator it; pat.associationLoop.getNext (assoc, it);) {
            if (!assoc.isNITPid ()) {
              //if (!assoc.isNITPid () && Scanning) {
              if (idx++ == pmtidx) {
                pmtpid = assoc.getPid ();
                pmtsid = assoc.getServiceId ();
                Add (pmtpid, 0x02);
                pmtnext = now + PMT_SCAN_TIMEOUT;
                LogI(3, prep("PMT pid now 0x%04x (idx=%d)\n"), pmtpid, pmtidx);
                break;
              }
            }
          }
          if (!pmtpid) {
            pmtidx = 0;
            pmtnext = now + PMT_SCAN_IDLE;
            LogI(1, prep("PMT scan idle\n"));

            Del (0, 0);  //this effectively kills the PMT_SCAN_IDLE functionality

            //now after the scan is completed, start processing
            ProcessNextFormat (true); //FirstTime flag is set
          }
        }
      }
    }
  } else if (pmtpid > 0 && Pid == pmtpid && Tid == SI::TableIdPMT && Source () && Transponder ()) {
    SI::PMT pmt (Data, false);
    if (pmt.CheckCRCAndParse () && pmt.getServiceId () == pmtsid) {
      SI::PMT::Stream stream;
      for (SI::Loop::Iterator it; pmt.streamLoop.getNext (stream, it);) {
        LogD(4, prep("StreamType: 0x%02x"), stream.getStreamType ());
        if (stream.getStreamType () == 0x05 || stream.getStreamType () == 0xc1) { //0x05 = Premiere, SKY, Freeview, Nagra 0xc1 = MHW1,MHW2;
          SI::CharArray data = stream.getData ();
          if ((data[1] & 0xE0) == 0xE0 && (data[3] & 0xF0) == 0xF0) {
            bool prvData = false, usrData = false;
            bool prvOTV = false, prvFRV = false;
            int usrOTV = 0, usrFRV = 0;
            if (data[2]==0x39) {//TODO Test This
              prvFRV = true;
              usrFRV = 1;
              LogD(4, prep("if (data[2]==0x39) {//TODO Test This"));
            }
            //Format = 0;               // 0 = premiere, 1 = MHW1, 2 = MHW2, 3 = Sky Italy (OpenTV), 4 = Sky UK (OpenTV), 5 = Freesat (Freeview), 6 = Nagraguide
            SI::Descriptor * d;
            unsigned char nDescriptorTag;
            for (SI::Loop::Iterator it; (d = stream.streamDescriptors.getNext (it));) {
              LogD(4, prep("EEPGDEBUG:d->getDescriptorTAG():%x,SI::PrivateTag:%x\n"), d->getDescriptorTag (), SI::PrivateDataSpecifierDescriptorTag);
              nDescriptorTag = d->getDescriptorTag ();
              switch (nDescriptorTag) {
              case SI::PrivateDataSpecifierDescriptorTag:
                //esyslog ("prv: %d %08x\n", d->getLength (), d->getData ().FourBytes (2));
                if (d->getLength () == 6 && d->getData ().FourBytes (2) == 0x000000be)
                  prvData = true;
                if (d->getLength () == 6 && d->getData ().FourBytes (2) == 0x4f545600) //OpenTV
                  prvOTV = true;
                if (d->getLength () == 6 && d->getData ().FourBytes (2) == 0x46534154) //Freeview
                  prvFRV = true;
                break;
              case 0x52:
                //if (d->getLength () == 3 && d->getData ().FourBytes (2) == 0xb07ea882) {
                if (d->getLength () == 3 && ((d->getData ().TwoBytes (2) & 0xff00) == 0xb000))
                  UnprocessedFormat[NAGRA] = stream.getPid ();
                break;
              case 0x90:
                //esyslog ("usr: %d %08x\n", d->getLength (), d->getData ().FourBytes (2));
                if (d->getLength () == 6 && d->getData ().FourBytes (2) == 0x0000ffff)
                  usrData = true;
                if (d->getLength () == 3 && ((d->getData ().TwoBytes (2) & 0xff00) == 0xb600)) //SKY IT //TODO ugly!
                  //if (d->getLength () == 3 && (d->getData ().TwoBytes (2) == 0xb6a5))   //SKY IT //TODO ugly!
                  usrOTV = SKY_IT;
                //Format = SKY_IT;
                if (d->getLength () == 3 && d->getData ().FourBytes (2) == 0xc004e288)       //SKY UK
                  usrOTV = SKY_UK;
                //Format = SKY_UK;
                break;
              case 0xc1: //MHW1, MHW2
//      esyslog("EEPGDEBUG:d->getDescriptorTAG:%d %08x\n",d->getLength(),d->getData().FourBytes(2));
                if (d->getLength () == 10 && d->getData ().FourBytes (2) == 0x50555348) //MHw1 Cyfra
                  UnprocessedFormat[MHW1] = stream.getPid ();
                break;
              case 0xc2: //MHW1, MHW2
                if (d->getLength () == 10 && d->getData ().FourBytes (2) == 0x45504700) //MHw1 CanDigNL and CSat
                  UnprocessedFormat[MHW1] = stream.getPid ();
                else if (d->getLength () == 10 && d->getData ().FourBytes (2) == 0x46494348) { //MHW2
                  UnprocessedFormat[MHW2] = stream.getPid ();
                }
                break;
              case 0xd1: //Freeview
                LogD(4, prep("case 0xd1: //Freeview"));
                if (d->getLength () == 3 && ((d->getData ().TwoBytes (2) & 0xff00) == 0x0100))
                  usrFRV = 0x01;
                //01 = EIT pid 3842
                //03 04 = SDT Service Description Table pid 3841
                //07 = still undocumented, definition of buch of transport streams pid 3840
                //02 = ATSC reserved, find out what huffman encoded text is sent here! pid 3843
                //05 06 = TOT Time Offset Table pid 3844
                break;

                /*       case 0xfe: //SKY_IT
                  if (d->getLength () == 6 && d->getData ().FourBytes (2) == 0x534b5900) { //SKY_IT
                    Format = SKY_IT;
                  }
                  break;*/
              default:
                break;
              }
              delete d;
            }
            if ((prvOTV) && ((usrOTV == SKY_IT) || (usrOTV == SKY_UK)))
              UnprocessedFormat[usrOTV] = stream.getPid ();
            else if (prvFRV)
              if (usrFRV == 0x01)
                UnprocessedFormat[FREEVIEW] = stream.getPid ();
            if (prvData && usrData)
              UnprocessedFormat[PREMIERE] = stream.getPid ();
            //TODO DPE DISH/BEV filters are always ON on provided transponders,
            // but there is no knowledge for the loop of the data at the moment.
            //EEPG:12472:H:S119.0W:20000:0:0:0:0:36862:4100:18:36862
            if (((Source() == cSource::FromString("S119.0W")
                && Transponder() == cChannel::Transponder(12472,'H'))
                || (Source() == cSource::FromString("S91.0W")
                && Transponder() == cChannel::Transponder(12224,'V')))
                && !UnprocessedFormat[DISH_BEV]) {
              UnprocessedFormat[DISH_BEV] = stream.getPid ();
            }

          }   //if data[1] && data [3]
        }   //if streamtype
      } //for loop that walks through streams
      NextPmt ();
      pmtnext = 0;
      /*      }
            else {
       Del (pmtpid, 0x02);
       Del (0, 0);
       pmtidx = 0;
       pmtnext = now + PMT_SCAN_IDLE;
       isyslog ("PMT scan forced idle\n");
            }*/
    } //checkCRC
  } //if pmtpid
  else if (Source ()) {

    if ( Pid == EIT_PID || Pid == 0x0300 || Pid == 0x0441 ) {
      if (Tid >= 0x4E)
        ProccessContinuous(Pid, Tid, Length, Data);
      return;
    }
    int Result;
    switch (Tid) {
    case 0xA0:
      if ((Pid < 0x30) || (Pid > 0x37)) {

        ProcessPremiere(Data);
        break;
      } //if citpid == 0xb11 Premiere
      /* no break - used for sky also*/
    case 0xa1:
    case 0xa2:
    case 0xa3:
      Result = GetTitlesSKYBOX (Data, Length - 4);
      if (Result != 1) //when fatal error or finished
        Del (Pid, 0xa0, 0xfc); //kill filter
      if (Result == 0) { //fatal error
        esyslog ("EEPG: Fatal error reading titles.");
        ProcessNextFormat (); //and go process other formats
      }
      if (Result == 2)
        AddFilter (Pid + 0x10, 0xa8, 0xfc); //Set filter that processes summaries of this batch
      break;
    case 0xa8:
    case 0xa9:
    case 0xaa:
    case 0xab:
      Result = GetSummariesSKYBOX (Data, Length - 4);
      if (Result != 1) //when fatal error or finished
        Del (Pid, 0xa8, 0xfc); //kill filter
      if (Result == 0) {
        esyslog ("EEPG: Fatal error reading summaries.");
        ProcessNextFormat ();
      }
      if (Result == 2) {
        LoadIntoSchedule ();
        if (Pid < 0x47) //this is not the last batch//FIXME chaining is easy on the PIDs and the CPU, but error when Pid,Tid is not used at the moment...
          AddFilter (Pid - 0x0F, 0xa0, 0xfc); //next pid, first tid
        else //last pid was processed
          ProcessNextFormat ();
      }
      break;
    case 0x90:
      if (Pid == 0xd2) {
        Result = GetTitlesMHW1 (Data, Length);
        if (Result != 1) //fatal error or last processed
          Del (Pid, Tid);
        if (Result == 0) {
          esyslog ("EEPG: Fatal error reading titles.");
          ProcessNextFormat ();
        }
        if (Result == 2)
          AddFilter (0xd3, 0x90); //SummariesMHW1
      } else if (Pid == 0xd3) {
        Result = GetSummariesMHW1 (Data, Length);
        if (Result != 1) //fatal error or last processed
          Del (Pid, Tid);
        if (Result == 0) {
          esyslog ("EEPG: Fatal error reading summaries.");
        }
        if (Result == 2) {
          LoadIntoSchedule ();
        }
        if (Result != 1) {
          ProcessNextFormat ();
        }
      }
      break;
    case 0xc8: //GetChannelsMHW2 or GetThemesMHW2
      if (Pid == 0x231) {
        if (Data[3] == 0x01) { //Themes it will be
          Result = GetThemesMHW2 (Data, Length); //return code 0 = fatal error, code 1 = sucess, code 2 = last item processed
          //break;
          if (Result != 1)
            EndThemes = true; //also set Endthemes on true on fatal error
        } //if Data
        else if (Data[3] == 0x00) { //Channels it will be
          Result = GetChannelsMHW (Data, Length, 2); //return code 0 = fatal error, code 1 = sucess, code 2 = last item processed
          if (Result != 1)
            EndChannels = true; //always remove filter, code 1 should never be returned since MHW2 always reads all channels..
          ChannelsOk = (Result == 2);
        }
        if (EndChannels && EndThemes) { //those are only set withing MHW2
          Del (0x231, 0xc8); //stop reading MHW2 themes and channels
          if (ChannelsOk) //No channels = fatal, no themes = nonfatal
            AddFilter (0x234, 0xe6); //start reading MHW2 titles
          else {
            esyslog ("EEPG: Fatal error reading channels.");
            ProcessNextFormat ();
          }
        }
      }    //if Pid == 0x231
      break;
    case 0x91:
      Result = GetChannelsMHW (Data, Length, 1); //return code 0 = fatal error, code 1 = sucess, code 2 = last item processed
      Del (Pid, Tid); //always remove filter, code 1 should never be returned since MHW1 always reads all channels...
      if (Result == 2)
        AddFilter (0xd2, 0x90); //TitlesMHW1
      else {
        esyslog ("EEPG: Fatal error reading channels.");
        ProcessNextFormat ();
      }
      break;
    case 0x92:
      Result = GetThemesMHW1 (Data, Length); //return code 0 = fatal error, code 1 = sucess, code 2 = last item processed
      if (Result != 1)
        Del (Pid, Tid);
      if (Result == 2)
        AddFilter (0xd3, 0x91); //ChannelsMHW1
      else {
        esyslog ("EEPG: Fatal error reading themes."); //doesnt have to be fatal...
        ProcessNextFormat ();
      }
      break;
    case 0xe6: //TitlesMHW2
      if (Pid == 0x234) {
        Result = GetTitlesMHW2 (Data, Length); //return code 0 = fatal error, code 1 = sucess, code 2 = last item processed
        if (Result != 1)
          Del (Pid, Tid);
        if (Result == 0) {
          esyslog ("EEPG: Fatal error reading titles.");
          ProcessNextFormat ();
        }
        if (Result == 2)
          AddFilter (0x236, 0x96); //start reading MHW2 summaries....
      }
      break;
    case 0x96: //Summaries MHW2
      if (Pid == 0x236) {
        Result = GetSummariesMHW2 (Data, Length); //return code 0 = fatal error, code 1 = sucess, code 2 = last item processed
        if (Result != 1)
          Del (Pid, Tid);
        if (Result == 0) {
          esyslog ("EEPG: Fatal error reading summaries.");
        }
        if (Result == 2)
          LoadIntoSchedule ();
        if (Result != 1) {
          ProcessNextFormat ();
        }
      } //if pid
      break;
    case 0x4a: //Sky channels
      if (Pid == 0x11) {
        Result = GetChannelsSKYBOX (Data, Length - 4);
        if (Result != 1) //only breakoff on completion or error; do NOT clean up after success, because then not all bouquets will be read
          Del (Pid, Tid); //Read all channels, clean up filter
        if (Result == 2) {
          GetThemesSKYBOX (); //Sky Themes from file; must be called AFTER first channels to have lThemes initialized FIXME
          if (InitDictionary ())
            AddFilter (0x30, 0xa0, 0xfc); //SKY Titles batch 0 of 7
          else {
            esyslog ("EEPG: Fatal error reading huffman table.");
            ProcessNextFormat ();
          }
        }

      } //if Pid == 0x11
      break;
    case 0xb0: //NagraGuide
      if (Pid == 0xc8) {
        Result = GetNagra (Data, Length);
        if (Result != 1)
          Del (Pid, Tid);
        if (Result == 0) {
          esyslog ("EEPG: Fatal error processing NagraGuide. End of processing.");
        }
        if (Result == 2) {
          ProcessNagra ();
          cSchedules::Cleanup (true); //deletes all past events
          isyslog ("EEPG: Ended processing Nagra");
        }
        if (Result != 1) {
          ProcessNextFormat ();
        }
      }
      break;

    case 0x4E:
    case 0x4F:
    case 0x50:
    case 0x51:
    case 0x52:
    case 0x53:
    case 0x54:
    case 0x55:
    case 0x56:
    case 0x57:
    case 0x58:
    case 0x59:
    case 0x5A:
    case 0x5B:
    case 0x5C:
    case 0x5D:
    case 0x5E:
    case 0x5F:
    case 0x60:
    case 0x61:
    case 0x62:
    case 0x63:
    case 0x64:
    case 0x65:
    case 0x66:
    case 0x67:
    case 0x68:
    case 0x69:
    case 0x6A:
    case 0x6B:
    case 0x6C:
    case 0x6D:
    case 0x6E:
    case 0x6F:
      // Freesat:
      // Set(3842, 0x4E, 0xFE);  // event info, actual(0x4E)/other(0x4F) TS, present/following
      // Set(3842, 0x50, 0xF0);  // event info, actual TS, schedule(0x50)/schedule for future days(0x5X)
      // Set(3842, 0x60, 0xF0);  // event info, other  TS, schedule(0x60)/schedule for future days(0x6X)
      //
      // PID found: 3841 (0x0f01)  [SECTION: Service Description Table (SDT) - other transport stream]
      // PID found: 3842 (0x0f02)  [SECTION: Event Information Table (EIT) - other transport stream, schedule]
      // PID found: 3843 (0x0f03)  [SECTION: ATSC reserved] TODO find out what compressed text info is here!
      // PID found: 3844 (0x0f04)  [SECTION: Time Offset Table (TOT)]

      if (Pid == 3842 || Pid == 0x39) {//0x39 Viasat, 0x0300 Dish Network EEPG, 0x0441 Bell ExpressVU EEPG
        ProccessContinuous(Pid, Tid, Length, Data);
      }
      break;

    default:
      break;
    } //end switch
  } //closes SOURCE()
} //end of closing

void cFilterEEPG::ProcessPremiere(const u_char *& Data)

{

  SI::PremiereCIT cit(Data, false);

  if (cit.CheckCRCAndParse ()) {
    cSchedulesLock SchedulesLock (true, 10);
    cSchedules *Schedules = (cSchedules *) cSchedules::Schedules (SchedulesLock);
    if (Schedules) {
      int now = time (0);
      int nCount = 0;
      int nRating = 0;
      unsigned char Tid = 0xa0; // TODO maybe default TableID
      SI::ExtendedEventDescriptors * ExtendedEventDescriptors = 0;
      SI::ShortEventDescriptor * ShortEventDescriptor = 0;
      char *order = 0, *rating = 0;
      {
        time_t firstTime = 0;
        SI::Descriptor * d;
        unsigned char nDescriptorTag;
        bool UseExtendedEventDescriptor = false;
        int LanguagePreferenceShort = -1;
        int LanguagePreferenceExt = -1;
        for (SI::Loop::Iterator it; (d = cit.eventDescriptors.getNext (it));) {
          nDescriptorTag = d->getDescriptorTag ();
          switch (nDescriptorTag) {
          case 0xF0: // order information
            if (SetupPE->OrderInfo) {
              static const char *text[] = {
                trNOOP ("Ordernumber"),
                trNOOP ("Price"),
                trNOOP ("Ordering"),
                trNOOP ("SMS"),
                trNOOP ("WWW")
              };
              char buff[512];
              int p = 0;
              const unsigned char *data = d->getData ().getData () + 2;
              for (int i = 0; i < 5; i++) {
                int l = data[0];
                if (l > 0)
                  p += snprintf (&buff[p], sizeof (buff) - p, "\n%s: %.*s", tr (text[i]), l, &data[1]);
                data += l + 1;
              }
              if (p > 0)
                order = strdup (buff);
            }
            break;
          case 0xF1: // parental rating
            if (SetupPE->RatingInfo) {
              char buff[512];
              int p = 0;
              const unsigned char *data = d->getData ().getData () + 2;
              nRating = data[0] + 3;
              p += snprintf (&buff[p], sizeof (buff) - p, "\n%s: %d %s", tr ("Rating"), nRating, tr ("years"));
              data += 7;
              int l = data[0];
              if (l > 0)
                p += snprintf (&buff[p], sizeof (buff) - p, " (%.*s)", l, &data[1]);
              if (p > 0)
                rating = strdup (buff);
            }
            break;
          case SI::PremiereContentTransmissionDescriptorTag:
            if (nCount >= 0) {
              SI::PremiereContentTransmissionDescriptor * pct = (SI::PremiereContentTransmissionDescriptor *) d;
              nCount++;
              SI::PremiereContentTransmissionDescriptor::StartDayEntry sd;
              SI::Loop::Iterator it;
              if (pct->startDayLoop.getNext (sd, it)) {
                SI::PremiereContentTransmissionDescriptor::StartDayEntry::StartTimeEntry st;
                SI::Loop::Iterator it2;
                if (sd.startTimeLoop.getNext (st, it2)) {
                  time_t StartTime = st.getStartTime (sd.getMJD ());
                  if (nCount == 1)
                    firstTime = StartTime;
                  else if (firstTime < StartTime - 5 * 50 || firstTime > StartTime + 5 * 60)
                    nCount = -1;
                }
              }
            }
            break;
          case SI::ExtendedEventDescriptorTag: {
            SI::ExtendedEventDescriptor * eed = (SI::ExtendedEventDescriptor *) d;
            if (I18nIsPreferredLanguage (Setup.EPGLanguages, eed->languageCode, LanguagePreferenceExt)
              || !ExtendedEventDescriptors) {
              delete ExtendedEventDescriptors;
              ExtendedEventDescriptors = new SI::ExtendedEventDescriptors;
              UseExtendedEventDescriptor = true;
            }
            if (UseExtendedEventDescriptor) {
              ExtendedEventDescriptors->Add (eed);
              d = NULL; // so that it is not deleted
            }
            if (eed->getDescriptorNumber () == eed->getLastDescriptorNumber ())
              UseExtendedEventDescriptor = false;
          }
          break;
          case SI::ShortEventDescriptorTag: {
            SI::ShortEventDescriptor * sed = (SI::ShortEventDescriptor *) d;
            if (I18nIsPreferredLanguage (Setup.EPGLanguages, sed->languageCode, LanguagePreferenceShort)
              || !ShortEventDescriptor) {
              delete ShortEventDescriptor;
              ShortEventDescriptor = sed;
              d = NULL; // so that it is not deleted
            }
          }
          break;
          default:
            break;
          }
          delete d;
        }
      }

      {
        bool Modified = false;
        int optCount = 0;
        unsigned int crc[3];
        crc[0] = cit.getContentId ();
        SI::PremiereContentTransmissionDescriptor * pct;
        for (SI::Loop::Iterator it;
          (pct =
            (SI::PremiereContentTransmissionDescriptor *) cit.eventDescriptors.getNext (it,
              SI::
              PremiereContentTransmissionDescriptorTag));) {
          int nid = pct->getOriginalNetworkId ();
          int tid = pct->getTransportStreamId ();
          int sid = pct->getServiceId ();
          if (SetupPE->FixEpg) {
            if (nid == 133) {
              if (tid == 0x03 && sid == 0xf0) {
                tid = 0x02;
                sid = 0xe0;
              } else if (tid == 0x03 && sid == 0xf1) {
                tid = 0x02;
                sid = 0xe1;
              } else if (tid == 0x03 && sid == 0xf5) {
                tid = 0x03;
                sid = 0xdc;
              } else if (tid == 0x04 && sid == 0xd2) {
                tid = 0x11;
                sid = 0xe2;
              } else if (tid == 0x11 && sid == 0xd3) {
                tid = 0x11;
                sid = 0xe3;
              }
            }
          }
          tChannelID channelID (Source (), nid, tid, sid);
          cChannel *channel = Channels.GetByChannelID (channelID, true);
#ifdef USE_NOEPG
          // only use epg from channels not blocked by noEPG-patch
          if (!allowedEPG (channelID))
            continue;
#endif /* NOEPG */

          if (!channel)
            continue;

          cSchedule *pSchedule = (cSchedule *) Schedules->GetSchedule (channelID);
          if (!pSchedule) {
            pSchedule = new cSchedule (channelID);
            Schedules->Add (pSchedule);
          }

          optCount++;
          SI::PremiereContentTransmissionDescriptor::StartDayEntry sd;
          int index = 0;
          for (SI::Loop::Iterator it; pct->startDayLoop.getNext (sd, it);) {
            int mjd = sd.getMJD ();
            SI::PremiereContentTransmissionDescriptor::StartDayEntry::StartTimeEntry st;
            for (SI::Loop::Iterator it2; sd.startTimeLoop.getNext (st, it2);) {
              time_t StartTime = st.getStartTime (mjd);
              time_t EndTime = StartTime + cit.getDuration ();
              int runningStatus =
                (StartTime < now && now < EndTime) ? SI::RunningStatusRunning :
                  ((StartTime - 30 < now && now < StartTime) ?
                    SI::RunningStatusStartsInAFewSeconds : SI::RunningStatusNotRunning);
              bool isOpt = false;
              if (index++ == 0 && nCount > 1)
                isOpt = true;
              crc[1] = isOpt ? optCount : 0;
              crc[2] = StartTime / STARTTIME_BIAS;
              tEventID EventId = ((('P' << 8) | 'W') << 16) | crc16 (0, (unsigned char *) crc, sizeof (crc));
              LogI(2, "%s R%d %04x/%.4x %d %d/%d %s +%d ", *channelID.ToString (), runningStatus,
                   EventId & 0xFFFF, cit.getContentId (), index, isOpt, optCount,
                   stripspace (ctime (&StartTime)), (int) cit.getDuration () / 60);
              if (EndTime + Setup.EPGLinger * 60 < now) {
                LogI(2, "(old)\n");
                continue;
              }

              bool newEvent = false;
              cEvent *pEvent = (cEvent *) pSchedule->GetEvent (EventId, -1);
              if (!pEvent) {
                LogI(2, "(new)\n");
                pEvent = new cEvent (EventId);
                if (!pEvent)
                  continue;
                newEvent = true;
              } else {
                LogI(2, "(upd)\n");
                pEvent->SetSeen ();
                if (pEvent->TableID () == 0x00 || pEvent->Version () == cit.getVersionNumber ()) {
                  if (pEvent->RunningStatus () != runningStatus)
                    pSchedule->SetRunningStatus (pEvent, runningStatus, channel);
                  continue;
                }
              }
              pEvent->SetEventID (EventId);
              pEvent->SetTableID (Tid);
              pEvent->SetVersion (cit.getVersionNumber ());
              pEvent->SetStartTime (StartTime);
              pEvent->SetDuration (cit.getDuration ());

              if (ShortEventDescriptor) {
                char buffer[256];
                ShortEventDescriptor->name.getText (buffer, sizeof (buffer));
                if (isOpt) {
                  char buffer2[sizeof (buffer) + 32];
                  snprintf (buffer2, sizeof (buffer2), optPats[SetupPE->OptPat], buffer, optCount);
                  pEvent->SetTitle (buffer2);
                } else
                  pEvent->SetTitle (buffer);
                LogI(2, "title: %s\n", pEvent->Title ());
                pEvent->SetShortText (ShortEventDescriptor->text.getText (buffer, sizeof (buffer)));
              }
              if (ExtendedEventDescriptors) {
                char buffer[ExtendedEventDescriptors->getMaximumTextLength (": ") + 1];
                pEvent->SetDescription (ExtendedEventDescriptors->getText (buffer, sizeof (buffer), ": "));
              }
              if (order || rating) {
                int len = (pEvent->Description ()? strlen (pEvent->Description ()) : 0) +
                  (order ? strlen (order) : 0) + (rating ? strlen (rating) : 0);
                char buffer[len + 32];
                buffer[0] = 0;
                if (pEvent->Description ())
                  strcat (buffer, pEvent->Description ());
                if (rating) {
                  strcat (buffer, rating);
                  pEvent->SetParentalRating(nRating);
                }
                if (order)
                  strcat (buffer, order);
                pEvent->SetDescription (buffer);
              }

              if (newEvent)
                pSchedule->AddEvent (pEvent);

              pEvent->FixEpgBugs ();
              if (pEvent->RunningStatus () != runningStatus)
                pSchedule->SetRunningStatus (pEvent, runningStatus, channel);
              pSchedule->DropOutdated (StartTime, EndTime, Tid, cit.getVersionNumber ());
              Modified = true;
            }
          }
          if (Modified) {
            pSchedule->Sort ();
            Schedules->SetModified (pSchedule);
          }
          delete pct;
        }
      }
      delete ExtendedEventDescriptors;
      delete ShortEventDescriptor;
      free (order);
      free (rating);
    }
  }

}

// --- cPluginEEPG ------------------------------------------------------

class cPluginEEPG:public cPlugin
{
private:
  struct {
    cFilterEEPG *filter;
    cDevice *device;
  } epg[MAXDVBDEVICES];

  void CheckCreateFile(const char* Name, const char *fileContent[]);

public:
  cPluginEEPG (void);
  virtual const char *Version (void) {
    return VERSION;
  }
  virtual const char *Description (void) {
    return tr (DESCRIPTION);
  }
  virtual bool Start (void);
  virtual void Stop (void);
  virtual cMenuSetupPage *SetupMenu (void);
  virtual bool SetupParse (const char *Name, const char *Value);
};

cPluginEEPG::cPluginEEPG (void)
{
  memset (epg, 0, sizeof (epg));
}

void cPluginEEPG::CheckCreateFile(const char* Name, const char *fileContent[])
{
  FILE *File;
  string FileName = string(cSetupEEPG::getInstance()->getConfDir()) + "/" + Name;
  File = fopen(FileName.c_str(), "r");
  if (File == NULL) {
    LogE (0, prep("Error opening file '%s', %s"), FileName.c_str(), strerror (errno));
    File = fopen (FileName.c_str(), "w");
    if (File == NULL) {
      LogE (0, prep("Error creating file '%s', %s"), FileName.c_str(), strerror (errno));
    } else {
      int i = 0;
      while (fileContent[i] != NULL) {
        fprintf (File, "%s\n", fileContent[i]);
        i++;
      }
      LogI (0, prep("Success creating file '%s'"), FileName.c_str());
      fclose (File);
    }
  } else {
    fclose (File);
  }
}

bool cPluginEEPG::Start (void)
{
#if APIVERSNUM < 10507
  RegisterI18n (Phrases);
#endif
  for (int i = 0; i < MAXDVBDEVICES; i++) {
    cDevice *dev = cDevice::GetDevice (i);
    if (dev) {
      epg[i].device = dev;
      dev->AttachFilter (epg[i].filter = new cFilterEEPG);
      isyslog ("Attached EEPG filter to device %d", i);
    }
  }
  char *ConfDir = NULL;
  // Initialize any background activities the plugin shall perform.
  DIR *ConfigDir;
  //if (ConfDir == NULL) {
  Asprintf (&ConfDir, "%s/eepg", cPlugin::ConfigDirectory ());
  //}
  ConfigDir = opendir (ConfDir);
  if (ConfigDir == NULL) {
    esyslog ("EEPG: Error opening directory '%s', %s", ConfDir, strerror (errno));
    if (mkdir (ConfDir, 0777) < 0) {
      esyslog ("EEPG: Error creating directory '%s', %s", ConfDir, strerror (errno));
    } else {
      isyslog ("EEPG: Success creating directory '%s'", ConfDir);
    }
  }
  cSetupEEPG::getInstance()->setConfDir(ConfDir);

  CheckCreateFile(EEPG_FILE_EQUIV, FileEquivalences);
  CheckCreateFile("sky_it.dict", SkyItDictionary);
  CheckCreateFile("sky_uk.dict", SkyUkDictionary);
  CheckCreateFile("sky_it.themes", SkyItThemes);
  CheckCreateFile("sky_uk.themes", SkyUkThemes);
  CheckCreateFile("freesat.t1", FreesatT1);
  CheckCreateFile("freesat.t2", FreesatT2);
  CheckCreateFile("sky_uk.themes", SkyUkThemes);

  sky_tables[0] = NULL;
  sky_tables[1] = NULL;
  tables[0][0] = NULL;
  //store all available sources, so when a channel is not found on current satellite, we can look for alternate sat positions.
  //perhaps this can be done smarter through existing VDR function???
  for (cChannel * Channel = Channels.First (); Channel; Channel = Channels.Next (Channel)) {
    if (!Channel->GroupSep ()) {
      bool found = false;
      for (int i = 0; (i < NumberOfAvailableSources) && (!found); i++)
        found = (Channel->Source () == AvailableSources[i]);
      if (!found)
        AvailableSources[NumberOfAvailableSources++] = Channel->Source ();
    }
  }
  if (CheckLevel(3))
    for (int i = 0; i < NumberOfAvailableSources; i++)
      isyslog ("EEPG: Available sources:%s.", *cSource::ToString (AvailableSources[i]));

#if APIVERSNUM > 10725
  new cEEpgHandler();
#endif
  EquivHandler =  new cEquivHandler();

  if (ConfDir) {
    free (ConfDir);
  }
  closedir(ConfigDir);
  return true;
}

void cPluginEEPG::Stop (void)
{
  for (int i = 0; i < MAXDVBDEVICES; i++) {
    cDevice *dev = epg[i].device;
    if (dev)
      dev->Detach (epg[i].filter);
    delete epg[i].filter;
    epg[i].device = 0;
    epg[i].filter = 0;
  }

  // Clean up after yourself!
//  if (ConfDir) {
//    free (ConfDir);
//  }
  if (sky_tables[0]) {
    free(sky_tables[0]);
  }
  if (sky_tables[1]) {
    free(sky_tables[1]);
  }
  if (EquivHandler) {
      delete EquivHandler;
  }

}

cMenuSetupPage *cPluginEEPG::SetupMenu (void)
{
  return new cMenuSetupPremiereEpg;
}

bool cPluginEEPG::SetupParse (const char *Name, const char *Value)
{
//  LogF(0, "!!!! Dime test LogF");
//  LogF(0, "!!!! Dime test LogF %d", 2);
//  LogI(0, "!!!! Dime test LogI");
//  LogI(0, "!!!! Dime test LogI %d", 2);
//  LogI(0, prep2("!!!! Dime test prep"));
//  LogI(0, prep2("!!!! Dime test prep %d"), 2);
//  LogD(0, "!!!! Dime test LogD");
//  LogD(0, "!!!! Dime test LogD %d", 2);
//  LogE(0, "!!!! Dime test LogE");
//  LogE(0, "!!!! Dime test LogE %d", 2);


  if (!strcasecmp (Name, "OptionPattern"))
    SetupPE->OptPat = atoi (Value);
  else if (!strcasecmp (Name, "OrderInfo"))
    SetupPE->OrderInfo = atoi (Value);
  else if (!strcasecmp (Name, "RatingInfo"))
    SetupPE->RatingInfo = atoi (Value);
  else if (!strcasecmp (Name, "FixEpg"))
    SetupPE->FixEpg = atoi (Value);
  else if (!strcasecmp (Name, "DisplayMessage"))
    SetupPE->DisplayMessage = atoi (Value);
#ifdef DEBUG
  else if (!strcasecmp (Name, "LogLevel"))
    SetupPE->LogLevel = atoi (Value);
  else if (!strcasecmp (Name, "ProcessEIT"))
    SetupPE->ProcessEIT = atoi (Value);
#endif
  else
    return false;
  return true;
}

VDRPLUGINCREATOR (cPluginEEPG); // Don't touch this!