This file is indexed.

/usr/share/perl5/XMLTV/IMDB.pm is in libxmltv-perl 0.5.70-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
#
# $Id: IMDB.pm,v 1.69 2015/07/12 00:59:01 knowledgejunkie Exp $
#
# The IMDB file contains two packages:
# 1. XMLTV::IMDB::Cruncher package which parses and manages IMDB "lists" files
#    from ftp.imdb.com
# 2. XMLTV::IMDB package that uses data files from the Cruncher package to
#    update/add details to XMLTV programme nodes.
#
# FUTURE - multiple hits on the same 'title only' could try and look for
#          character names matching from description to imdb.com character
#          names.
#
# FUTURE - multiple hits on 'title only' should probably pick latest
#          tv series over any older ones. May make for better guesses.
#
# BUG - we identify 'presenters' by the word "Host" appearing in the character
#       description. For some movies, character names include the word Host.
#       ex. Animal, The (2001) has a character named "Badger Milk Host".
#
# BUG - if there is a matching title with > 1 entry (say made for tv-movie and
#       at tv-mini series) made in the same year (or even "close" years) it is
#       possible for us to pick the wrong one we should pick the one with the
#       closest year, not just the first closest match based on the result ordering
#       for instance Ghost Busters was made in 1984, and into a tv series in
#       1986. if we have a list of GhostBusters 1983, we should pick the 1984 movie
#       and not 1986 tv series...maybe :) but currently we'll pick the first
#       returned close enough match instead of trying the closest date match of
#       the approx hits.
#

use strict;

package XMLTV::IMDB;

use open ':encoding(iso-8859-1)';   # try to enforce file encoding (does this work in Perl <5.8.1? )

#
# HISTORY
# .6 = what was here for the longest time
# .7 = fixed file size est calculations
#    = moviedb.info now includes _file_size_uncompressed values for each downloaded file
# .8 = updated file size est calculations
#    = moviedb.dat directors and actors list no longer include repeated names (which mostly
#      occured in episodic tv programs (reported by Alexy Khrabrov)
# .9 = added keywords data
# .10 = added plot data
#
our $VERSION = '0.10';      # version number of database

sub new
{
    my ($type) = shift;
    my $self={ @_ };            # remaining args become attributes

    for ('imdbDir', 'verbose') {
	die "invalid usage - no $_" if ( !defined($self->{$_}));
    }
    #$self->{verbose}=2;
    $self->{replaceDates}=0        if ( !defined($self->{replaceDates}));
    $self->{replaceTitles}=0       if ( !defined($self->{replaceTitles}));
    $self->{replaceCategories}=0   if ( !defined($self->{replaceCategories}));
    $self->{replaceKeywords}=0     if ( !defined($self->{replaceKeywords}));
    $self->{replaceURLs}=0         if ( !defined($self->{replaceURLs}));
    $self->{replaceDirectors}=1    if ( !defined($self->{replaceDirectors}));
    $self->{replaceActors}=0       if ( !defined($self->{replaceActors}));
    $self->{replacePresentors}=1   if ( !defined($self->{replacePresentors}));
    $self->{replaceCommentators}=1 if ( !defined($self->{replaceCommentators}));
    $self->{replaceStarRatings}=0  if ( !defined($self->{replaceStarRatings}));
    $self->{replacePlot}=0         if ( !defined($self->{replacePlot}));

    $self->{updateDates}=1        if ( !defined($self->{updateDates}));
    $self->{updateTitles}=1       if ( !defined($self->{updateTitles}));
    $self->{updateCategories}=1   if ( !defined($self->{updateCategories}));
    $self->{updateCategoriesWithGenres}=1 if ( !defined($self->{updateCategoriesWithGenres}));
    $self->{updateKeywords}=0     if ( !defined($self->{updateKeywords}));          # default is to NOT add keywords
    $self->{updateURLs}=1         if ( !defined($self->{updateURLs}));
    $self->{updateDirectors}=1    if ( !defined($self->{updateDirectors}));
    $self->{updateActors}=1       if ( !defined($self->{updateActors}));
    $self->{updatePresentors}=1   if ( !defined($self->{updatePresentors}));
    $self->{updateCommentators}=1 if ( !defined($self->{updateCommentators}));
    $self->{updateStarRatings}=1  if ( !defined($self->{updateStarRatings}));
    $self->{updatePlot}=0         if ( !defined($self->{updatePlot}));          # default is to NOT add plot

    $self->{numActors}=3          if ( !defined($self->{numActors}));           # default is to add top 3 actors

    $self->{moviedbIndex}="$self->{imdbDir}/moviedb.idx";
    $self->{moviedbData}="$self->{imdbDir}/moviedb.dat";
    $self->{moviedbInfo}="$self->{imdbDir}/moviedb.info";
    $self->{moviedbOffline}="$self->{imdbDir}/moviedb.offline";

    # default is not to cache lookups
    $self->{cacheLookups}=0 if ( !defined($self->{cacheLookups}) );
    $self->{cacheLookupSize}=0 if ( !defined($self->{cacheLookupSize}) );

    $self->{cachedLookups}->{tv_series}->{_cacheSize_}=0;

    bless($self, $type);

    $self->{categories}={'movie'          =>'Movie',
			 'tv_movie'       =>'TV Movie', # made for tv
			 'video_movie'    =>'Video Movie', # went straight to video or was made for it
			 'tv_series'      =>'TV Series',
			 'tv_mini_series' =>'TV Mini Series'};

    $self->{stats}->{programCount}=0;

    for my $cat (keys %{$self->{categories}}) {
	$self->{stats}->{perfect}->{$cat}=0;
	$self->{stats}->{close}->{$cat}=0;
    }
    $self->{stats}->{perfectMatches}=0;
    $self->{stats}->{closeMatches}=0;

    $self->{stats}->{startTime}=time();

    return($self);
}

sub loadDBInfo($)
{
    my $file=shift;
    my $info;

    open(INFO, "< $file") || return("imdbDir index file \"$file\":$!\n");
    while(<INFO>) {
	chop();
	if ( s/^([^:]+)://o ) {
	    $info->{$1}=$_;
	}
    }
    close(INFO);
    return($info);
}

sub checkIndexesOkay($)
{
    my $self=shift;
    if ( ! -d "$self->{imdbDir}" ) {
	return("imdbDir \"$self->{imdbDir}\" does not exist\n");
    }

    if ( -f "$self->{moviedbOffline}" ) {
	return("imdbDir index offline: check $self->{moviedbOffline} for details");
    }

    for my $file ($self->{moviedbIndex}, $self->{moviedbData}, $self->{moviedbInfo}) {
	if ( ! -f "$file" ) {
	    return("imdbDir index file \"$file\" does not exist\n");
	}
    }

    $VERSION=~m/^(\d+)\.(\d+)$/o || die "package corrupt, VERSION string invalid ($VERSION)";
    my ($major, $minor)=($1, $2);

    my $info=loadDBInfo($self->{moviedbInfo});
    return($info) if ( ref $info eq 'SCALAR' );

    if ( !defined($info->{db_version}) ) {
	return("imdbDir index db missing version information, rerun --prepStage all\n");
    }
    if ( $info->{db_version}=~m/^(\d+)\.(\d+)$/o ) {
	if ( $1 != $major || $2 < $minor ) {
	    return("imdbDir index db requires updating, rerun --prepStage all\n");
	}
	if ( $1 == 0 && $2 == 1 ) {
	    return("imdbDir index db requires update, rerun --prepStage 5 (bug:actresses never appear)\n");
	}
	if ( $1 == 0 && $2 == 2 ) {
	    # 0.2 -> 0.3 upgrade requires prepStage 5 to be re-run
	    return("imdbDir index db requires minor reindexing, rerun --prepStage 3 and 5\n");
	}
	if ( $1 == 0 && $2 == 3 ) {
	    # 0.2 -> 0.3 upgrade requires prepStage 5 to be re-run
	    return("imdbDir index db requires major reindexing, rerun --prepStage 2 and new prepStages 5,6,7,8 and 9\n");
	}
	if ( $1 == 0 && $2 == 4 ) {
	    # 0.2 -> 0.3 upgrade requires prepStage 5 to be re-run
	    return("imdbDir index db corrupt (got version 0.4), rerun --prepStage all\n");
	}
	# okay
	return(undef);
    }
    else {
	return("imdbDir index version of '$info->{db_version}' is invalid, rerun --prepStage all\n".
	       "if problem persists, submit bug report to xmltv-devel\@lists.sf.net\n");
    }
}

sub basicVerificationOfIndexes($)
{
    my $self=shift;

    # check that the imdbdir is invalid and up and running
    my $title="Army of Darkness";
    my $year=1992;

    $self->openMovieIndex() || return("basic verification of indexes failed\n".
				      "database index isn't readable");

    my $verbose = $self->{verbose}; $self->{verbose} = 0;
    my $res=$self->getMovieMatches($title, $year);
    $self->{verbose} = $verbose; undef $verbose;
    if ( !defined($res) ) {
	$self->closeMovieIndex();
	return("basic verification of indexes failed\n".
	       "no match for basic verification of movie \"$title, $year\"\n");
    }
    if ( !defined($res->{exactMatch}) ) {
	$self->closeMovieIndex();
	return("basic verification of indexes failed\n".
	       "no exact match for movie \"$title, $year\"\n");
    }
    if ( scalar(@{$res->{exactMatch}})!= 1) {
	$self->closeMovieIndex();
	return("basic verification of indexes failed\n".
	       "got more than one exact match for movie \"$title, $year\"\n");
    }
    my @exact=@{$res->{exactMatch}};
    if ( $exact[0]->{title} ne $title ) {
	$self->closeMovieIndex();
	return("basic verification of indexes failed\n".
	       "title associated with key \"$title, $year\" is bad\n");
    }

    if ( $exact[0]->{year} ne "$year" ) {
	$self->closeMovieIndex();
	return("basic verification of indexes failed\n".
	       "year associated with key \"$title, $year\" is bad\n");
    }

    my $id=$exact[0]->{id};
    $res=$self->getMovieIdDetails($id);
    if ( !defined($res) ) {
	$self->closeMovieIndex();
	return("basic verification of indexes failed\n".
	       "no movie details for movie \"$title, $year\" (id=$id)\n");
    }

    if ( !defined($res->{directors}) ) {
	$self->closeMovieIndex();
	return("basic verification of indexes failed\n".
	       "movie details didn't provide any director for movie \"$title, $year\" (id=$id)\n");
    }
    if ( !$res->{directors}[0]=~m/Raimi/o ) {
	$self->closeMovieIndex();
	return("basic verification of indexes failed\n".
	       "movie details didn't show Raimi as the main director for movie \"$title, $year\" (id=$id)\n");
    }
    if ( !defined($res->{actors}) ) {
	$self->closeMovieIndex();
	return("basic verification of indexes failed\n".
	       "movie details didn't provide any cast movie \"$title, $year\" (id=$id)\n");
    }
    if ( !$res->{actors}[0]=~m/Campbell/o ) {
	$self->closeMovieIndex();
	return("basic verification of indexes failed\n".
	       "movie details didn't show Bruce Campbell as the main actor in movie \"$title, $year\" (id=$id)\n");
    }
    my $matches=0;
    for (@{$res->{genres}}) {
	if ( $_ eq "Action" ||
	     $_ eq "Comedy" ||
	     $_ eq "Fantasy" ||
	     $_ eq "Horror" ||
	     $_ eq "Romance" ) {
	    $matches++;
	}
    }
    if ( $matches == 0 ) {
	$self->closeMovieIndex();
	return("basic verification of indexes failed\n".
	       "movie details didn't show genres correctly for movie \"$title, $year\" (id=$id)\n");
    }
    if ( !defined($res->{ratingDist}) ||
	 !defined($res->{ratingVotes}) ||
	 !defined($res->{ratingRank}) ) {
	$self->closeMovieIndex();
	return("basic verification of indexes failed\n".
	       "movie details didn't show imdbratings for movie \"$title, $year\" (id=$id)\n");
    }
    $self->closeMovieIndex();
    return(undef);

}

sub sanityCheckDatabase($)
{
    my $self=shift;
    my $errline;

    $errline=$self->checkIndexesOkay();
    return($errline) if ( defined($errline) );
    $errline=$self->basicVerificationOfIndexes();
    return($errline) if ( defined($errline) );

    # all okay
    return(undef);
}

sub error($$)
{
    print STDERR "tv_imdb: $_[1]\n";
}

sub status($$)
{
    if ( $_[0]->{verbose} ) {
	print STDERR "tv_imdb: $_[1]\n";
    }
}

sub debug($$)
{
    my $self=shift;
    my $mess=shift;
    if ( $self->{verbose} > 1 ) {
	print STDERR "tv_imdb: $mess\n";
    }
}

use Search::Dict;

sub openMovieIndex($)
{
    my $self=shift;

    if ( !open($self->{INDEX_FD}, "< $self->{moviedbIndex}") ) {
	return(undef);
    }
    if ( !open($self->{DBASE_FD}, "< $self->{moviedbData}") ) {
	close($self->{INDEX_FD});
	return(undef);
    }
    return(1);
}

sub closeMovieIndex($)
{
    my $self=shift;

    close($self->{INDEX_FD});
    delete($self->{INDEX_FD});

    close($self->{DBASE_FD});
    delete($self->{DBASE_FD});

    return(1);
}

# moviedbIndex file has the format:
# title:lineno
# where key is a url encoded title followed by the year of production and a colon
sub getMovieMatches($$$)
{
    my $self=shift;
    my $title=shift;
    my $year=shift;

    # Articles are put at the end of a title ( in all languages )
    #$match=~s/^(The|A|Une|Las|Les|Los|L\'|Le|La|El|Das|De|Het|Een)\s+(.*)$/$2, $1/og;

    my $match="$title";
    if ( defined($year) ) {
	$match.=" ($year)";
    }

    # to encode s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/oeg
    # to decode s/%(?:([0-9a-fA-F]{2})|u([0-9a-fA-F]{4}))/defined($1)? chr hex($1) : utf8_chr(hex($2))/oge;

    # url encode
    $match=lc($match);
    $match=~s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/oeg;

    $self->debug("looking for \"$match\" in $self->{moviedbIndex}");
    if ( !$self->{INDEX_FD} ) {
	die "internal error: index not open";
    }

    my $FD=$self->{INDEX_FD};
    Search::Dict::look(*{$FD}, $match, 0, 0);
    my $results;
    while (<$FD>) {
	last if ( !m/^$match/ );

	chop();
	my @arr=split('\t', $_);
	if ( scalar(@arr) != 5 ) {
	    warn "$self->{moviedbIndex} corrupt (correct key:$_)";
	    next;
	}

	if ( $arr[0] eq $match ) {
	    # return title and id
	    #$arr[1]=~s/(.*),\s*(The|A|Une|Las|Les|Los|L\'|Le|La|El|Das|De|Het|Een)$/$2 $1/og;

	    #$arr[0]=~s/%(?:([0-9a-fA-F]{2})|u([0-9a-fA-F]{4}))/defined($1)? chr hex($1) : utf8_chr(hex($2))/oge;
	    #$self->debug("exact:$arr[1] ($arr[2]) qualifier=$arr[3] id=$arr[4]");
	    my $title=$arr[1];
	    if ( $title=~s/\s+\((\d\d\d\d|\?\?\?\?)\)$//o ) {
	    }
	    elsif ( $title=~s/\s+\((\d\d\d\d|\?\?\?\?)\/[IVX]+\)$//o ) {
	    }
	    else {
		die "unable to decode year from title key \"$title\", report to xmltv-devel\@lists.sf.net";
	    }
	    $title=~s/(.*),\s*(The|A|Une|Las|Les|Los|L\'|Le|La|El|Das|De|Het|Een)$/$2 $1/og;
	    $self->debug("exact:$title ($arr[2]) qualifier=$arr[3] id=$arr[4]");
	    push(@{$results->{exactMatch}}, {'key'=> $arr[1],
					     'title'=>$title,
					     'year'=>$arr[2],
					     'qualifier'=>$arr[3],
					     'id'=>$arr[4]});
	}
	else {
	    # decode
	    #s/%(?:([0-9a-fA-F]{2})|u([0-9a-fA-F]{4}))/defined($1)? chr hex($1) : utf8_chr(hex($2))/oge;
	    # return title
	    #$arr[1]=~s/(.*),\s*(The|A|Une|Las|Les|Los|L\'|Le|La|El|Das|De|Het|Een)$/$2 $1/og;
	    #$arr[0]=~s/%(?:([0-9a-fA-F]{2})|u([0-9a-fA-F]{4}))/defined($1)? chr hex($1) : utf8_chr(hex($2))/oge;
	    #$self->debug("close:$arr[1] ($arr[2]) qualifier=$arr[3] id=$arr[4]");
	    my $title=$arr[1];

	    if ( $title=~m/^\"/o && $title=~m/\"\s*\(/o ) { #"
		$title=~s/^\"//o; #"
		$title=~s/\"(\s*\()/$1/o; #"
	    }

	    if ( $title=~s/\s+\((\d\d\d\d|\?\?\?\?)\)$//o ) {
	    }
	    elsif ( $title=~s/\s+\((\d\d\d\d|\?\?\?\?)\/[IVX]+\)$//o ) {
	    }
	    else {
		die "unable to decode year from title key \"$title\", report to xmltv-devel\@lists.sf.net";
	    }
	    $title=~s/(.*),\s*(The|A|Une|Las|Les|Los|L\'|Le|La|El|Das|De|Het|Een)$/$2 $1/og;
	    $self->debug("close:$title ($arr[2]) qualifier=$arr[3] id=$arr[4]");
	    push(@{$results->{closeMatch}}, {'key'=> $arr[1],
					     'title'=>$title,
					     'year'=>$arr[2],
					     'qualifier'=>$arr[3],
					     'id'=>$arr[4]});
	}
    }
    #print "MovieMatches on ($match) = ".Dumper($results)."\n";
    return($results);
}

sub getMovieExactMatch($$$)
{
    my $self=shift;
    my $title=shift;
    my $year=shift;
    my $res=$self->getMovieMatches($title, $year);

    return(undef) if ( !defined($res) );
    if ( !defined($res->{exactMatch}) ) {
	return(undef);
    }
    if ( scalar(@{$res->{exactMatch}}) != 1 ) {
	return(undef);
    }
    return($res->{exactMatch}[0]);
}

sub getMovieCloseMatches($$)
{
    my $self=shift;
    my $title=shift;

    my $res=$self->getMovieMatches($title, undef) || return(undef);

    if ( defined($res->{exactMatch})) {
	die "corrupt imdb database - hit on \"$title\"";
    }
    return(undef) if ( !defined($res->{closeMatch}) );
    my @arr=@{$res->{closeMatch}};
    #print "CLOSE DUMP=".Dumper(@arr)."\n";
    return(@arr);
}

sub getMovieIdDetails($$)
{
    my $self=shift;
    my $id=shift;

    if ( !$self->{DBASE_FD} ) {
	die "internal error: index not open";
    }
    my $results;
    my $FD=$self->{DBASE_FD};
    Search::Dict::look(*{$FD}, "$id:", 0, 0);
    while (<$FD>) {
	last if ( !m/^$id:/ );
	chop();
	if ( s/^$id:// ) {
	    my ($directors, $actors, $genres, $ratingDist, $ratingVotes, $ratingRank, $keywords, $plot)=split('\t', $_);
	    if ( $directors ne "<>" ) {
		for my $name (split('\|', $directors)) {
		    # remove (I) etc from imdb.com names (kept in place for reference)
		    $name=~s/\s\([IVX]+\)$//o;
		    # switch name around to be surname last
		    $name=~s/^([^,]+),\s*(.*)$/$2 $1/o;
		    push(@{$results->{directors}}, $name);
		}
	    }
	    if ( $actors ne "<>" ) {
		for my $name (split('\|', $actors)) {
		    # remove (I) etc from imdb.com names (kept in place for reference)
		    my $HostNarrator;
		    if ( $name=~s/\[([^\]]+)\]$//o ) {
			$HostNarrator=$1;
		    }
		    $name=~s/\s\([IVX]+\)$//o;

		    # switch name around to be surname last
		    $name=~s/^([^,]+),\s*(.*)$/$2 $1/o;
		    if ( $HostNarrator ) {
			if ( $HostNarrator=~s/,*Host//o ) {
			    push(@{$results->{presenter}}, $name);
			}
			if ( $HostNarrator=~s/,*Narrator//o ) {
			    push(@{$results->{commentator}}, $name);
			}
		    }
		    else {
			push(@{$results->{actors}}, $name);
		    }
		}
	    }
	    if ( $genres ne "<>" ) {
		push(@{$results->{genres}}, split('\|', $genres));
	    }
	    if ( $keywords ne "<>" ) {
		push(@{$results->{keywords}}, split(',', $keywords));
	    }
	    $results->{ratingDist}=$ratingDist if ( $ratingDist ne "<>" );
	    $results->{ratingVotes}=$ratingVotes if ( $ratingVotes ne "<>" );
	    $results->{ratingRank}=$ratingRank if ( $ratingRank ne "<>" );
	    $results->{plot}=$plot if ( $plot ne "<>" );
	}
	else {
	    warn "lookup of movie (id=$id) resulted in garbage ($_)";
	}
    }
    if ( !defined($results) ) {
	# some movies we don't have any details for
	$results->{noDetails}=1;
    }
    #print "MovieDetails($id) = ".Dumper($results)."\n";
    return($results);
}

#
# FUTURE - close hit could be just missing or extra
#          punctuation:
#       "Run Silent, Run Deep" for imdb's "Run Silent Run Deep"
#       "Cherry, Harry and Raquel" for imdb's "Cherry, Harry and Raquel!"
#       "Cat Women of the Moon" for imdb's "Cat-Women of the Moon"
#       "Baywatch Hawaiian Wedding" for imdb's "Baywatch: Hawaiian Wedding" :)
#
# FIXED - "Victoria and Albert" appears for imdb's "Victoria & Albert" (and -> &)
# FIXED - "Columbo Cries Wolf" appears instead of "Columbo:Columbo Cries Wolf"
# FIXED - Place the article last, for multiple languages. For instance
#         Los amantes del círculo polar -> amantes del círculo polar, Los
# FIXED - common international vowel changes. For instance
#          "Anna Karénin" (é->e)
#
sub alternativeTitles($)
{
    my $title=shift;
    my @titles;

    push(@titles, $title);

    # try the & -> and conversion
    if ( $title=~m/\&/o ) {
	my $t=$title;
	while ( $t=~s/(\s)\&(\s)/$1and$2/o ) {
	    push(@titles, $t);
	}
    }

    # try the and -> & conversion
    if ( $title=~m/\sand\s/io ) {
	my $t=$title;
	while ( $t=~s/(\s)and(\s)/$1\&$2/io ) {
	    push(@titles, $t);
	}
    }

    # try the "Columbo: Columbo cries Wolf" -> "Columbo cries Wolf" conversion
    my $max=scalar(@titles);
    for (my $i=0; $i<$max ; $i++) {
	my $t=$titles[$i];
        if ( $t=~m/^[^:]+:.+$/io ) {
            while ( $t=~s/^[^:]+:\s*(.+)\s*$/$1/io ) {
                push(@titles, $t);
            }
        }
    }

    # Place the articles last
    $max=scalar(@titles);
    for (my $i=0; $i<$max ; $i++) {
	my $t=$titles[$i];
        if ( $t=~m/^(The|A|Une|Les|Los|Las|L\'|Le|La|El|Das|De|Het|Een)\s+(.*)$/io ) {
            $t=~s/^(The|A|Une|Les|Los|Las|L\'|Le|La|El|Das|De|Het|Een)\s+(.*)$/$2, $1/iog;
            push(@titles, $t);
        }
        if ( $t=~m/^(.+),\s*(The|A|Une|Les|Los|Las|L\'|Le|La|El|Das|De|Het|Een)$/io ) {
            $t=~s/^(.+),\s*(The|A|Une|Les|Los|Las|L\'|Le|La|El|Das|De|Het|Een)$/$2 $1/iog;
            push(@titles, $t);
        }
    }

    # convert all the special language characters
    $max=scalar(@titles);
    for (my $i=0; $i<$max ; $i++) {
	my $t=$titles[$i];
	if ( $t=~m/[ÀÁÂÃÄÅàáâãäåÈÉÊËèéêëÌÍÎÏìíîïÒÓÔÕÖØòóôõöøÙÚÛÜùúûüÆæÇçÑñßÝýÿ]/io ) {
	    $t=~s/[ÀÁÂÃÄÅàáâãäå]/a/gio;
	    $t=~s/[ÈÉÊËèéêë]/e/gio;
	    $t=~s/[ÌÍÎÏìíîï]/i/gio;
	    $t=~s/[ÒÓÔÕÖØòóôõöø]/o/gio;
	    $t=~s/[ÙÚÛÜùúûü]/u/gio;
	    $t=~s/[Ææ]/ae/gio;
	    $t=~s/[Çç]/c/gio;
	    $t=~s/[Ññ]/n/gio;
	    $t=~s/[ß]/ss/gio;
	    $t=~s/[Ýýÿ]/y/gio;
	    $t=~s/[¿]//gio;
	    push(@titles, $t);
	}
    }

    # optional later possible titles include removing the '.' from titles
    # ie "Project V.I.P.E.R." matching imdb "Project VIPER"
    $max=scalar(@titles);
    for (my $i=0; $i<$max ; $i++) {
	my $t=$titles[$i];
	if ( $t=~s/\.//go ) {
	    push(@titles,$t);
	}
    }
    return(\@titles);
}

sub findMovieInfo($$$$)
{
    my ($self, $title, $year, $exact)=@_;

    my @titles=@{alternativeTitles($title)};

    if ( $exact == 1 ) {
	# try an exact match first :)
	for my $mytitle ( @titles ) {
	    my $info=$self->getMovieExactMatch($mytitle, $year);
	    if ( defined($info) ) {
		if ( $info->{qualifier} eq "movie" ) {
		    $self->status("perfect hit on movie \"$info->{key}\"");
		    $info->{matchLevel}="perfect";
		    return($info);
		}
		elsif ( $info->{qualifier} eq "tv_movie" ) {
		    $self->status("perfect hit on made-for-tv-movie \"$info->{key}\"");
		    $info->{matchLevel}="perfect";
		    return($info);
		}
		elsif ( $info->{qualifier} eq "video_movie" ) {
		    $self->status("perfect hit on made-for-video-movie \"$info->{key}\"");
		    $info->{matchLevel}="perfect";
		    return($info);
		}
		elsif ( $info->{qualifier} eq "video_game" ) {
		    next;
		}
		elsif ( $info->{qualifier} eq "tv_series" ) {
		}
		elsif ( $info->{qualifier} eq "tv_mini_series" ) {
		}
		else {
		    $self->error("$self->{moviedbIndex} responded with wierd entry for \"$info->{key}\"");
		    $self->error("weird trailing qualifier \"$info->{qualifier}\"");
		    $self->error("submit bug report to xmltv-devel\@lists.sf.net");
		}
	    }
	    $self->debug("no exact title/year hit on \"$mytitle ($year)\"");
	}
	return(undef);
    }
    elsif ( $exact == 2 ) {
	# looking for first exact match on the title, don't have a year to compare

	for my $mytitle ( @titles ) {
	    # try close hit if only one :)
	    my $cnt=0;
	    my @closeMatches=$self->getMovieCloseMatches("$mytitle");

	    # we traverse the hits twice, first looking for success,
	    # then again to produce warnings about missed close matches
	    for my $info (@closeMatches) {
		next if ( !defined($info) );
		$cnt++;

		# within one year with exact match good enough
		if ( lc($mytitle) eq lc($info->{title}) ) {

		    if ( $info->{qualifier} eq "movie" ) {
			$self->status("close enough hit on movie \"$info->{key}\" (since no 'date' field present)");
			$info->{matchLevel}="close";
			return($info);
		    }
		    elsif ( $info->{qualifier} eq "tv_movie" ) {
			$self->status("close enough hit on made-for-tv-movie \"$info->{key}\" (since no 'date' field present)");
			$info->{matchLevel}="close";
			return($info);
		    }
		    elsif ( $info->{qualifier} eq "video_movie" ) {
			$self->status("close enough hit on made-for-video-movie \"$info->{key}\" (since no 'date' field present)");
			$info->{matchLevel}="close";
			return($info);
		    }
		    elsif ( $info->{qualifier} eq "video_game" ) {
			next;
		    }
		    elsif ( $info->{qualifier} eq "tv_series" ) {
		    }
		    elsif ( $info->{qualifier} eq "tv_mini_series" ) {
		    }
		    else {
			$self->error("$self->{moviedbIndex} responded with wierd entry for \"$info->{key}\"");
			$self->error("weird trailing qualifier \"$info->{qualifier}\"");
			$self->error("submit bug report to xmltv-devel\@lists.sf.net");
		    }
		}
	    }
	}
	# nothing worked
	return(undef);
    }

    # otherwise we're looking for a title match with a close year
    for my $mytitle ( @titles ) {
	# try close hit if only one :)
	my $cnt=0;
	my @closeMatches=$self->getMovieCloseMatches("$mytitle");

	# we traverse the hits twice, first looking for success,
	# then again to produce warnings about missed close matches
	for my $info (@closeMatches) {
	    next if ( !defined($info) );
	    $cnt++;

	    # within one year with exact match good enough
	    if ( lc($mytitle) eq lc($info->{title}) ) {
		my $yearsOff=abs(int($info->{year})-$year);

		$info->{matchLevel}="close";

		if ( $yearsOff <= 2 ) {
		    my $showYear=int($info->{year});

		    if ( $info->{qualifier} eq "movie" ) {
			$self->status("close enough hit on movie \"$info->{key}\" (off by $yearsOff years)");
			return($info);
		    }
		    elsif ( $info->{qualifier} eq "tv_movie" ) {
			$self->status("close enough hit on made-for-tv-movie \"$info->{key}\" (off by $yearsOff years)");
			return($info);
		    }
		    elsif ( $info->{qualifier} eq "video_movie" ) {
			$self->status("close enough hit on made-for-video-movie \"$info->{key}\" (off by $yearsOff years)");
			return($info);
		    }
		    elsif ( $info->{qualifier} eq "video_game" ) {
			$self->status("ignoring close hit on video-game \"$info->{key}\"");
			next;
		    }
		    elsif ( $info->{qualifier} eq "tv_series" ) {
			$self->status("ignoring close hit on tv series \"$info->{key}\"");
			#$self->status("close enough hit on tv series \"$info->{key}\" (off by $yearsOff years)");
		    }
		    elsif ( $info->{qualifier} eq "tv_mini_series" ) {
			$self->status("ignoring close hit on tv mini-series \"$info->{key}\"");
			#$self->status("close enough hit on tv mini-series \"$info->{key}\" (off by $yearsOff years)");
		    }
		    else {
			$self->error("$self->{moviedbIndex} responded with wierd entry for \"$info->{key}\"");
			$self->error("weird trailing qualifier \"$info->{qualifier}\"");
			$self->error("submit bug report to xmltv-devel\@lists.sf.net");
		    }
		}
	    }
	}

	# if we found at least something, but nothing matched
	# produce warnings about missed, but close matches
	for my $info (@closeMatches) {
	    next if ( !defined($info) );

	    # within one year with exact match good enough
	    if ( lc($mytitle) eq lc($info->{title}) ) {
		my $yearsOff=abs(int($info->{year})-$year);
		if ( $yearsOff <= 2 ) {
		    #die "internal error: key \"$info->{key}\" failed to be processed properly";
		}
		elsif ( $yearsOff <= 5 ) {
		    # report these as status
		    $self->status("ignoring close, but not good enough hit on \"$info->{key}\" (off by $yearsOff years)");
		}
		else {
		    # report these as debug messages
		    $self->debug("ignoring close hit on \"$info->{key}\" (off by $yearsOff years)");
		}
	    }
	    else {
		$self->debug("ignoring close hit on \"$info->{key}\" (title did not match)");
	    }
	}
    }
    #$self->status("failed to lookup \"$title ($year)\"");
    return(undef);
}

sub findTVSeriesInfo($$)
{
    my ($self, $title)=@_;

    if ( $self->{cacheLookups} ) {
	my $id=$self->{cachedLookups}->{tv_series}->{$title};

	if ( defined($id) ) {
	    #print STDERR "REF= (".ref($id).")\n";
	    if ( $id ne '' ) {
		return($id);
	    }
	    return(undef);
	}
    }

    my @titles=@{alternativeTitles($title)};

    # try an exact match first :)
    my $idInfo;

    for my $mytitle ( @titles ) {
	# try close hit if only one :)
	my $cnt=0;
	my @closeMatches=$self->getMovieCloseMatches("$mytitle");

	for my $info (@closeMatches) {
	    next if ( !defined($info) );
	    $cnt++;

	    if ( lc($mytitle) eq lc($info->{title}) ) {

		$info->{matchLevel}="perfect";

		if ( $info->{qualifier} eq "movie" ) {
		    #$self->status("ignoring close hit on movie \"$info->{key}\"");
		}
		elsif ( $info->{qualifier} eq "tv_movie" ) {
		    #$self->status("ignoring close hit on tv movie \"$info->{key}\"");
		}
		elsif ( $info->{qualifier} eq "video_movie" ) {
		    #$self->status("ignoring close hit on made-for-video-movie \"$info->{key}\"");
		}
		elsif ( $info->{qualifier} eq "video_game" ) {
		    #$self->status("ignoring close hit on made-for-video-movie \"$info->{key}\"");
		    next;
		}
		elsif ( $info->{qualifier} eq "tv_series" ) {
		    $idInfo=$info;
		    $self->status("perfect hit on tv series \"$info->{key}\"");
		    last;
		}
		elsif ( $info->{qualifier} eq "tv_mini_series" ) {
		    $idInfo=$info;
		    $self->status("perfect hit on tv mini-series \"$info->{key}\"");
		    last;
		}
		else {
		    $self->error("$self->{moviedbIndex} responded with wierd entry for \"$info->{key}\"");
		    $self->error("weird trailing qualifier \"$info->{qualifier}\"");
		    $self->error("submit bug report to xmltv-devel\@lists.sf.net");
		}
	    }
	}
	last if ( defined($idInfo) );
    }

    if ( $self->{cacheLookups} ) {
	# flush cache after this lookup if its gotten too big
	if ( $self->{cachedLookups}->{tv_series}->{_cacheSize_} >
	     $self->{cacheLookupSize} ) {
	    delete($self->{cachedLookups}->{tv_series});
	    $self->{cachedLookups}->{tv_series}->{_cacheSize_}=0;
	}
	if ( defined($idInfo) ) {
	    $self->{cachedLookups}->{tv_series}->{$title}=$idInfo;
	}
	else {
	    $self->{cachedLookups}->{tv_series}->{$title}="";
	}
	$self->{cachedLookups}->{tv_series}->{_cacheSize_}++;
    }
    if ( defined($idInfo) ) {
	return($idInfo);
    }
    else {
	#$self->status("failed to lookup tv series \"$title\"");
	return(undef);
    }
}

#
# todo - add country of origin
# todo - video (colour/aspect etc) details
# todo - audio (stereo) details
# todo - ratings ? - use certificates.list
# todo - add description - plot summaries ? - which one do we choose ?
# todo - writer
# todo - producer
# todo - running time (duration)
# todo - identify 'Host' and 'Narrator's and put them in as
#        credits:presenter and credits:commentator resp.
# todo - check program length - probably a warning if longer ?
#        can we update length (separate from runnning time in the output ?)
# todo - icon - url from www.imdb.com of programme image ?
#        this could be done by scraping for the hyper linked poster
#        <a name="poster"><img src="http://ia.imdb.com/media/imdb/01/I/60/69/80m.jpg" height="139" width="99" border="0"></a>
#        and grabbin' out the img entry. (BTW ..../npa.jpg seems to line up with no poster available)
#
#
sub applyFound($$$)
{
    my ($self, $prog, $idInfo)=@_;

    my $title=$prog->{title}->[0]->[0];

    if ( $self->{updateDates} ) {
	my $date;

	# don't add dates only fix them for tv_series
	if ( $idInfo->{qualifier} eq "movie" ||
	     $idInfo->{qualifier} eq "video_movie" ||
	     $idInfo->{qualifier} eq "tv_movie" ) {
	    #$self->debug("adding 'date' field (\"$idInfo->{year}\") on \"$title\"");
	    $date=int($idInfo->{year});
	}
	else {
	    #$self->debug("not adding 'date' field to $idInfo->{qualifier} \"$title\"");
	    $date=undef;
	}

	if ( $self->{replaceDates} ) {
	    if ( defined($prog->{date}) && defined($date) ) {
		$self->debug("replacing 'date' field");
		delete($prog->{date});
		$prog->{date}=$date;
	    }
	}
	else {
	    # only set date if not already defined
	    if ( !defined($prog->{date}) && defined($date) ) {
		$prog->{date}=$date;
	    }
	}
    }

    if ( $self->{updateTitles} ) {
	if ( $idInfo->{title} ne $title ) {
	    if ( $self->{replaceTitles} ) {
		$self->debug("replacing (all) 'title' from \"$title\" to \"$idInfo->{title}\"");
		delete($prog->{title});
	    }

	    my @list;

	    push(@list, [$idInfo->{title}, undef]);

	    if ( defined($prog->{title}) ) {
		my $name=$idInfo->{title};
		my $found=0;
		for my $v (@{$prog->{title}}) {
		    if ( lc($v->[0]) eq lc($name) ) {
			$found=1;
		    }
		    else {
			push(@list, $v);
		    }
		}
	    }
	    $prog->{title}=\@list;
	}
    }

    if ( $self->{updateURLs} ) {
	if ( $self->{replaceURLs} ) {
	    if ( defined($prog->{url}) ) {
		$self->debug("replacing (all) 'url'");
		delete($prog->{url});
	    }
	}

	# add url to programme on www.imdb.com
	my $url=$idInfo->{key};

	$url=~s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/oeg;
	$url="http://us.imdb.com/M/title-exact?".$url;

	if ( defined($prog->{url}) ) {
	    my @rep;
	    push(@rep, $url);
	    for (@{$prog->{url}}) {
		# skip urls for imdb.com that we're probably safe to replace
		if ( !m;^http://us.imdb.com/M/title-exact;o ) {
		    push(@rep, $_);
		}
	    }
	    $prog->{url}=\@rep;
	}
	else {
	    push(@{$prog->{url}}, $url);
	}
    }

    # squirrel away movie qualifier so its first on the list of replacements
    my @categories;
    push(@categories, [$self->{categories}->{$idInfo->{qualifier}}, 'en']);
    if ( !defined($self->{categories}->{$idInfo->{qualifier}}) ) {
	die "how did we get here with an invalid qualifier '$idInfo->{qualifier}'";
    }

    my $details=$self->getMovieIdDetails($idInfo->{id});
    if ( $details->{noDetails} ) {
	# we don't have any details on this movie
    }
    else {
	# add directors list
	if ( $self->{updateDirectors} && defined($details->{directors}) ) {
	    # only update directors if we have exactly one or if
	    # its a movie of some kind, add more than one.
	    if ( scalar(@{$details->{directors}}) == 1 ||
		 $idInfo->{qualifier} eq "movie" ||
		 $idInfo->{qualifier} eq "video_movie" ||
		 $idInfo->{qualifier} eq "tv_movie" ) {

		if ( $self->{replaceDirectors} ) {
		    if ( defined($prog->{credits}->{director}) ) {
			$self->debug("replacing director(s)");
			delete($prog->{credits}->{director});
		    }
		}

		my @list;
		# add top 3 billing directors list form www.imdb.com
		for my $name (splice(@{$details->{directors}},0,3)) {
		    push(@list, $name);
		}

		# preserve all existing directors listed if we did't already have them.
		if ( defined($prog->{credits}->{director}) ) {
		    for my $name (@{$prog->{credits}->{director}}) {
			my $found=0;
			for(@list) {
			    if ( lc eq lc($name) ) {
				$found=1;
			    }
			}
			if ( !$found ) {
			    push(@list, $name);
			}
		    }
		}
		$prog->{credits}->{director}=\@list;
	    }
	    else {
		$self->debug("not adding 'director' field to $idInfo->{qualifier} \"$title\"");
	    }
	}

	if ( $self->{updateActors} && defined($details->{actors}) ) {
	    if ( $self->{replaceActors} ) {
		if ( defined($prog->{credits}->{actor}) ) {
		    $self->debug("replacing actor(s) on $idInfo->{qualifier} \"$idInfo->{key}\"");
		    delete($prog->{credits}->{actor});
		}
	    }

	    my @list;
	    # add top billing actors (default = 3) from www.imdb.com
	    for my $name (splice(@{$details->{actors}},0,$self->{numActors})) {
		push(@list, $name);
	    }
	    # preserve all existing actors listed if we did't already have them.
	    if ( defined($prog->{credits}->{actor}) ) {
		for my $name (@{$prog->{credits}->{actor}}) {
		    my $found=0;
		    for(@list) {
			if ( lc eq lc($name) ) {
			    $found=1;
			}
		    }
		    if ( !$found ) {
			push(@list, $name);
		    }
		}
	    }
	    $prog->{credits}->{actor}=\@list;
	}

	if ( $self->{updatePresentors} && defined($details->{presenter}) ) {
	    if ( $self->{replacePresentors} ) {
		if ( defined($prog->{credits}->{presenter}) ) {
		    $self->debug("replacing presentor");
		    delete($prog->{credits}->{presenter});
		}
	    }
	    $prog->{credits}->{presenter}=$details->{presenter};
	}
	if ( $self->{updateCommentators} && defined($details->{commentator}) ) {
	    if ( $self->{replaceCommentators} ) {
		if ( defined($prog->{credits}->{commentator}) ) {
		    $self->debug("replacing commentator");
		    delete($prog->{credits}->{commentator});
		}
	    }
	    $prog->{credits}->{commentator}=$details->{commentator};
	}

	# push genres as categories
	if ( $self->{updateCategoriesWithGenres} ) {
	    if ( defined($details->{genres}) ) {
		for (@{$details->{genres}}) {
		    push(@categories, [$_, 'en']);
		}
	    }
	}

	if ( $self->{updateStarRatings} && defined($details->{ratingRank}) ) {
	    if ( $self->{replaceStarRatings} ) {
		if ( defined($prog->{'star-rating'}) ) {
		    $self->debug("replacing 'star-rating'");
		    delete($prog->{'star-rating'});
		}
		unshift( @{$prog->{'star-rating'}}, [ $details->{ratingRank} . "/10", 'IMDB User Rating' ] );
	    }
	    else {
	        # add IMDB User Rating in front of all other star-ratings
		unshift( @{$prog->{'star-rating'}}, [ $details->{ratingRank} . "/10", 'IMDB User Rating' ] );
	    }
	}

    if ( $self->{updateKeywords} ) {
        my @keywords;
        if ( defined($details->{keywords}) ) {
            for (@{$details->{keywords}}) {
                push(@keywords, [$_, 'en']);
            }
        }

        if ( $self->{replaceKeywords} ) {
            if ( defined($prog->{keywords}) ) {
                $self->debug("replacing (all) 'keywords'");
                delete($prog->{keywords});
            }
        }
        if ( defined($prog->{keyword}) ) {
	    for my $value (@{$prog->{keyword}}) {
		my $found=0;
		for my $k (@keywords) {
		    if ( lc($k->[0]) eq lc($value->[0]) ) {
			$found=1;
		    }
		}
		if ( !$found ) {
		    push(@keywords, $value);
		}
	    }
	}
	$prog->{keyword}=\@keywords;
    }

        if ( $self->{updatePlot} ) {
            # plot is held as a <desc> entity
            # if 'replacePlot' then delete all existing <desc> entities and add new
            # else add this plot as an additional <desc> entity
            #
            if ( $self->{replacePlot} ) {
                if ( defined($prog->{desc}) ) {
                    $self->debug("replacing (all) 'desc'");
                    delete($prog->{desc});
                }
            }
            if ( defined($details->{plot}) ) {
                # check it's not already there
                my $found = 0;
                for my $_desc ( @{$prog->{desc}} ) {
                    $found = 1  if ( @{$_desc}[0] eq $details->{plot} );
                }
                push @{$prog->{desc}}, [ $details->{plot}, 'en' ]  if !$found;
            }
        }

    }

    if ( $self->{updateCategories} ) {
	if ( $self->{replaceCategories} ) {
	    if ( defined($prog->{category}) ) {
		$self->debug("replacing (all) 'category'");
		delete($prog->{category});
	    }
	}
	if ( defined($prog->{category}) ) {
	    for my $value (@{$prog->{category}}) {
		my $found=0;
		#print "checking category $value->[0] with $mycategory\n";
		for my $c (@categories) {
		    if ( lc($c->[0]) eq lc($value->[0]) ) {
			$found=1;
		    }
		}
		if ( !$found ) {
		    push(@categories, $value);
		}
	    }
	}
	$prog->{category}=\@categories;
    }

    return($prog);
}

sub augmentProgram($$$)
{
    my ($self, $prog, $movies_only)=@_;

    $self->{stats}->{programCount}++;

    # assume first title in first language is the one we want.
    my $title=$prog->{title}->[0]->[0];

    if ( defined($prog->{date}) && $prog->{date}=~m/^\d\d\d\d$/o ) {

	# for programs with dates we try:
	# - exact matches on movies
	# - exact matches on tv series
	# - close matches on movies
	my $id=$self->findMovieInfo($title, $prog->{date}, 1); # exact match
	if ( !defined($id) ) {
	    $id=$self->findTVSeriesInfo($title);
	    if ( !defined($id) ) {
		$id=$self->findMovieInfo($title, $prog->{date}, 0); # close match
	    }
	}
	if ( defined($id) ) {
	    $self->{stats}->{$id->{matchLevel}."Matches"}++;
	    $self->{stats}->{$id->{matchLevel}}->{$id->{qualifier}}++;
	    return($self->applyFound($prog, $id));
	}
	$self->status("failed to find a match for movie \"$title ($prog->{date})\"");
	return(undef);
	# fall through and try again as a tv series
    }

    if ( !$movies_only ) {
	my $id=$self->findTVSeriesInfo($title);
	if ( defined($id) ) {
	    $self->{stats}->{$id->{matchLevel}."Matches"}++;
	    $self->{stats}->{$id->{matchLevel}}->{$id->{qualifier}}++;
	    return($self->applyFound($prog, $id));
	}

	if ( 0 ) {
	    # this has hard to support 'close' results, unless we know
	    # for certain we're looking for a movie (ie duration etc)
	    # this is a bad idea.
	    my $id=$self->findMovieInfo($title, undef, 2); # any title match
	    if ( defined($id) ) {
		$self->{stats}->{$id->{matchLevel}."Matches"}++;
		$self->{stats}->{$id->{matchLevel}}->{$id->{qualifier}}++;
		return($self->applyFound($prog, $id));
	    }
	}
	$self->status("failed to find a match for show \"$title\"");
    }
    return(undef);
}

#
# todo - add in stats on other things added (urls ?, actors, directors,categories)
#        separate out from what was added or updated
#
sub getStatsLines($)
{
    my $self=shift;
    my $totalChannelsParsed=shift;

    my $endTime=time();
    my %stats=%{$self->{stats}};

    my $ret=sprintf("Checked %d programs, on %d channels\n", $stats{programCount}, $totalChannelsParsed);

    for my $cat (sort keys %{$self->{categories}}) {
	$ret.=sprintf("  found %d %s titles", $stats{perfect}->{$cat}+$stats{close}->{$cat},
		      $self->{categories}->{$cat});
	if ( $stats{close}->{$cat} != 0 ) {
	    if ( $stats{close}->{$cat} == 1 ) {
		$ret.=sprintf(" (%d was not perfect)", $stats{close}->{$cat});
	    }
	    else {
		$ret.=sprintf(" (%d were not perfect)", $stats{close}->{$cat});
	    }
	}
	$ret.="\n";
    }

    $ret.=sprintf("  augmented %.2f%% of the programs, parsing %.2f programs/sec\n",
		  ($stats{programCount}!=0)?(($stats{perfectMatches}+$stats{closeMatches})*100)/$stats{programCount}:0,
		  ($endTime!=$stats{startTime} && $stats{programCount} != 0)?
		  $stats{programCount}/($endTime-$stats{startTime}):0);

    return($ret);
}

1;

# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

package XMLTV::IMDB::Crunch;
use LWP;

use open ':encoding(iso-8859-1)';   # try to enforce file encoding (does this work in Perl <5.8.1? )

# Use Term::ProgressBar if installed.
use constant Have_bar => eval {
    require Term::ProgressBar;
    $Term::ProgressBar::VERSION >= 2;
};

#
# This package parses and manages to index imdb plain text files from
# ftp.imdb.com/interfaces. (see http://www.imdb.com/interfaces for
# details)
#
# I might, given time build a download manager that:
#    - downloads the latest plain text files
#    - understands how to download each week's diffs and apply them
# Currently, the 'downloadMissingFiles' flag in the hash of attributes
# passed triggers a simple-minded downloader.
#
# I may also roll this project into a xmltv-free imdb-specific
# perl interface that just supports callbacks and understands more of
# the imdb file formats.
#

sub new
{
    my ($type) = shift;
    my $self={ @_ };            # remaining args become attributes
    for ($self->{downloadMissingFiles}) {
	$_=0 if not defined; # default
    }

    for ('imdbDir', 'verbose') {
	die "invalid usage - no $_" if ( !defined($self->{$_}));
    }

    $self->{stageLast} = 9;     # set the final stage in the build - i.e. the one which builds the final database
    $self->{stages} = { 1=>'movies', 2=>'directors', 3=>'actors', 4=>'actresses', 5=>'genres', 6=>'ratings', 7=>'keywords', 8=>'plot' };
    $self->{optionalStages} = { 'keywords' => 7, 'plot' => 8 };     # list of optional stages - no need to download files for these

    $self->{moviedbIndex}="$self->{imdbDir}/moviedb.idx";
    $self->{moviedbData}="$self->{imdbDir}/moviedb.dat";
    $self->{moviedbInfo}="$self->{imdbDir}/moviedb.info";
    $self->{moviedbOffline}="$self->{imdbDir}/moviedb.offline";

    # only leave progress bar on if its available
    if ( !Have_bar ) {
	$self->{showProgressBar}=0;
    }

    bless($self, $type);

    if ( $self->{stageToRun} ne $self->{stageLast} ) {
        # unless this is the last stage, check we have the necessary files
        return(undef)  if ( $self->checkFiles() != 0 );
    }

    return($self);
}


sub checkFiles () {

    my ($self)=@_;

    if ( ! -d "$self->{imdbDir}" ) {
	if ( $self->{downloadMissingFiles} ) {
	    warn "creating directory $self->{imdbDir}\n";
	    mkdir $self->{imdbDir}, 0777
	      or die "cannot mkdir $self->{imdbDir}: $!";
	}
	else {
	    die "$self->{imdbDir}:does not exist";
	}
    }
    my $listsDir = "$self->{imdbDir}/lists";
    if ( ! -d $listsDir ) {
	mkdir $listsDir, 0777 or die "cannot mkdir $listsDir: $!";
    }

  CHECK_FILES:
    my %missingListFiles; # maps 'movies' to filename ...movies.gz

    FILES_CHECK:
    while ( my( $key, $value ) = each %{ $self->{stages} } ) {
        # don't check *all* files - only the ones we are crunching
        next FILES_CHECK  if ( lc($self->{stageToRun}) ne 'all' && $key != int($self->{stageToRun}) );
	my $file=$value;
	my $filename="$listsDir/$file.list";
	my $filenameGz="$filename.gz";
	my $filenameExists = -f $filename;
	my $filenameSize = -s $filename;
	my $filenameGzExists = -f $filenameGz;
	my $filenameGzSize = -s $filenameGz;

	if ( $filenameExists and not $filenameSize ) {
	    warn "removing zero-length $filename\n";
	    unlink $filename or die "cannot unlink $filename: $!";
	    $filenameExists = 0;
	}
	if ( $filenameGzExists and not $filenameGzSize ) {
	    warn "removing zero-length $filenameGz\n";
	    unlink $filenameGz or die "cannot unlink $filenameGz: $!";
	    $filenameGzExists = 0;
	}

	if ( not $filenameExists and not $filenameGzExists ) {
	    # Just report one of the filenames, keep the message simple.
	    warn "$filenameGz does not exist\n";
            if ( $self->{optionalStages}{$file} ) {
                warn "$file will not be added to database\n";
            } else {
                $missingListFiles{$file}=$filenameGz;
	}
	}
	elsif ( not $filenameExists and $filenameGzExists ) {
	    $self->{imdbListFiles}->{$file}=$filenameGz;
	}
	elsif ( $filenameExists and not $filenameGzExists ) {
	    $self->{imdbListFiles}->{$file}=$filename;
	}
	elsif ( $filenameExists and $filenameGzExists ) {
	    die "both $filename and $filenameGz exist, remove one of them\n";
	}
	else { die }
    }
    if ( $self->{downloadMissingFiles} ) {
	my $baseUrl = 'ftp://ftp.fu-berlin.de/pub/misc/movies/database';
	foreach ( sort keys %missingListFiles ) {
	    my $url = "$baseUrl/$_.list.gz";
	    my $filename = delete $missingListFiles{$_};
	    my $partial = "$filename.partial";
	    if (-e $partial) {
		if (not -s $partial) {
		    print STDERR "removing empty $partial\n";
		    unlink $partial or die "cannot unlink $partial: $!";
		}
		else {
		    die <<END
$partial already exists, remove it or try renaming to $filename and
resuming the download of <$url> by hand.

END
  ;
		}
	    }

	    print STDERR <<END
Trying to download <$url>.
With a slow network link this could fail; it might be better to
download the file by hand and save it as
$filename.

END
  ;
	    # For downloading we use LWP
	    #
	    my $ua = LWP::UserAgent->new();
	    $ua->env_proxy();
	    $ua->show_progress(1);

	    my $req = HTTP::Request->new(GET => $url);
	    $req->authorization_basic('anonymous', 'tv_imdb');

	    my $resp = $ua->request($req, $filename);
	    my $got_size = -s $filename;
	    if (defined $resp and $resp->is_success ) {
		die if not $got_size;
		print STDERR "<$url>\n\t-> $filename, success\n\n";
	    }
	    else {
		my $msg = "failed to download $url to $filename";
		$msg .= ", http response code: ".$resp->status_line if defined $resp;
		warn $msg;
		if ($got_size) {
		    warn "renaming $filename -> $partial\n";
		    rename $filename, $partial
		      or die "cannot rename $filename to $partial: $!";
		    warn "You might try continuing the download of <$url> manually.\n";
		}
		exit(1);
	    }
	}
	$self->{downloadMissingFiles} = 0;
	goto CHECK_FILES;
    }

    if ( %missingListFiles ) {
	print STDERR "tv_imdb: requires you to download the above files from ftp.imdb.com\n";
	print STDERR "         see http://www.imdb.com/interfaces for details\n";
        print STDERR "         or try the --download option\n";
	#return(undef);
        return 1;
    }

    return 0;
}

sub redirect($$)
{
    my ($self, $file)=@_;

    if ( defined($file) ) {
	if ( !open($self->{logfd}, "> $file") ) {
	    print STDERR "$file:$!\n";
	    return(0);
	}
	$self->{errorCountInLog}=0;
    }
    else {
	close($self->{logfd});
	$self->{logfd}=undef;
    }
    return(1);
}

sub error($$)
{
    my $self=shift;
    if ( defined($self->{logfd}) ) {
	print {$self->{logfd}} $_[0]."\n";
	$self->{errorCountInLog}++;
    }
    else {
	print STDERR $_[0]."\n";
    }
}

sub status($$)
{
    my $self=shift;

    if ( $self->{verbose} ) {
	print STDERR $_[0]."\n";
    }
}

sub withThousands ($)
{
    my ($val) = @_;
    $val =~ s/(\d{1,3}?)(?=(\d{3})+$)/$1,/g;
    return $val;
}

use XMLTV::Gunzip;
use IO::File;

sub openMaybeGunzip($)
{
    for ( shift ) {
	return gunzip_open($_) if m/\.gz$/;
	return new IO::File("< $_");
    }
}

sub closeMaybeGunzip($$)
{
    if ( $_[0]=~m/\.gz$/o ) {
	# Would close($fh) but that causes segfaults on my system.
	# Investigating, but in the meantime just leave it open.
	#
	#return gunzip_close($_[1]);
    }

    # Apparently this can also segfault (wtf?).
    #return close($_[1]);
}

sub readMoviesOrGenres($$$$)
{
    my ($self, $whichMoviesOrGenres, $countEstimate, $file)=@_;
    my $startTime=time();
    my $header;
    my $whatAreWeParsing;
    my $lineCount=0;

    if ( $whichMoviesOrGenres eq "Movies" ) {
	$header="MOVIES LIST";
	$whatAreWeParsing=1;
    }
    elsif ( $whichMoviesOrGenres eq "Genres" ) {
	$header="8: THE GENRES LIST";
	$whatAreWeParsing=2;
    }
    my $fh = openMaybeGunzip($file) || return(-2);
    while(<$fh>) {
	$lineCount++;
	if ( m/^$header/ ) {
	    if ( !($_=<$fh>) || !m/^===========/o ) {
		$self->error("missing ======= after $header at line $lineCount");
		closeMaybeGunzip($file, $fh);
		return(-1);
	    }
	    if ( !($_=<$fh>) || !m/^\s*$/o ) {
		$self->error("missing empty line after ======= at line $lineCount");
		closeMaybeGunzip($file, $fh);
		return(-1);
	    }
	    last;
	}
	elsif ( $lineCount > 1000 ) {
	    $self->error("$file: stopping at line $lineCount, didn't see \"$header\" line");
	    closeMaybeGunzip($file, $fh);
	    return(-1);
	}
    }

    my $progress=Term::ProgressBar->new({name  => "parsing $whichMoviesOrGenres",
					 count => $countEstimate,
					 ETA   => 'linear'})
	if ( $self->{showProgressBar} );

    $progress->minor(0) if ($self->{showProgressBar});
    $progress->max_update_rate(1) if ($self->{showProgressBar});
    my $next_update=0;

    my $count=0;
    while(<$fh>) {
	$lineCount++;
	my $line=$_;
	#print "read line $lineCount:$line\n";

	# end is line consisting of only '-'
	last if ( $line=~m/^\-\-\-\-\-\-\-+/o );

	$line=~s/\n$//o;

	my $tab=index($line, "\t");
	if ( $tab != -1 ) {
	    my $mkey=substr($line, 0, $tab);

	    next if ($mkey=~m/\s*\{\{SUSPENDED\}\}/o);

	    if ( $whatAreWeParsing == 2 ) {
		# don't see what these are...?
		# ignore {{SUSPENDED}}
		$mkey=~s/\s*\{\{SUSPENDED\}\}//o;

		# ignore {Twelve Angry Men (1954)}
		$mkey=~s/\s*\{[^\}]+\}//go;

		# skip enties that have {} in them since they're tv episodes
		#next if ( $mkey=~s/\s*\{[^\}]+\}$//o );

		my $genre=substr($line, $tab);

		# genres sometimes has more than one tab
		$genre=~s/^\t+//og;
		if ( defined($self->{movies}{$mkey}) ) {
		    $self->{movies}{$mkey}.="|".$genre;
		}
		else {
		    $self->{movies}{$mkey}=$genre;
		    # returned count is number of unique titles found
		    $count++;
		}
	    }
	    else {
		push(@{$self->{movies}}, $mkey);
		# returned count is number of titles found
		$count++;
	    }

	    if ( $self->{showProgressBar} ) {
		# re-adjust target so progress bar doesn't seem too wonky
		if ( $count > $countEstimate ) {
		    $countEstimate = $progress->target($count+1000);
		    $next_update=$progress->update($count);
		}
		elsif ( $count > $next_update ) {
		    $next_update=$progress->update($count);
		}
	    }
	}
	else {
	    $self->error("$file:$lineCount: unrecognized format (missing tab)");
	    $next_update=$progress->update($count) if ($self->{showProgressBar});
	}
    }
    $progress->update($countEstimate) if ($self->{showProgressBar});

    $self->status(sprintf("parsing $whichMoviesOrGenres found ".withThousands($count)." titles in ".
			  withThousands($lineCount)." lines in %d seconds",time()-$startTime));

    closeMaybeGunzip($file, $fh);
    return($count);
}

sub readCastOrDirectors($$$)
{
    my ($self, $whichCastOrDirector, $castCountEstimate, $file)=@_;
    my $startTime=time();

    my $header;
    my $whatAreWeParsing;
    my $lineCount=0;

    if ( $whichCastOrDirector eq "Actors" ) {
	$header="THE ACTORS LIST";
	$whatAreWeParsing=1;
    }
    elsif ( $whichCastOrDirector eq "Actresses" ) {
	$header="THE ACTRESSES LIST";
	$whatAreWeParsing=2;
    }
    elsif ( $whichCastOrDirector eq "Directors" ) {
	$header="THE DIRECTORS LIST";
	$whatAreWeParsing=3;
    }
    else {
	die "why are we here ?";
    }

    my $fh = openMaybeGunzip($file) || return(-2);
    my $progress=Term::ProgressBar->new({name  => "parsing $whichCastOrDirector",
					 count => $castCountEstimate,
					 ETA   => 'linear'})
      if ($self->{showProgressBar});
    $progress->minor(0) if ($self->{showProgressBar});
    $progress->max_update_rate(1) if ($self->{showProgressBar});
    my $next_update=0;
    while(<$fh>) {
	$lineCount++;
	if ( m/^$header/ ) {
	    if ( !($_=<$fh>) || !m/^===========/o ) {
		$self->error("missing ======= after $header at line $lineCount");
		closeMaybeGunzip($file, $fh);
		return(-1);
	    }
	    if ( !($_=<$fh>) || !m/^\s*$/o ) {
		$self->error("missing empty line after ======= at line $lineCount");
		closeMaybeGunzip($file, $fh);
		return(-1);
	    }
	    if ( !($_=<$fh>) || !m/^Name\s+Titles\s*$/o ) {
		$self->error("missing name/titles line after ======= at line $lineCount");
		closeMaybeGunzip($file, $fh);
		return(-1);
	    }
	    if ( !($_=<$fh>) || !m/^[\s\-]+$/o ) {
		$self->error("missing name/titles suffix line after ======= at line $lineCount");
		closeMaybeGunzip($file, $fh);
		return(-1);
	    }
	    last;
	}
	elsif ( $lineCount > 1000 ) {
	    $self->error("$file: stopping at line $lineCount, didn't see \"$header\" line");
	    closeMaybeGunzip($file, $fh);
	    return(-1);
	}
    }

    my $cur_name;
    my $count=0;
    my $castNames=0;
    while(<$fh>) {
	$lineCount++;
	my $line=$_;
	$line=~s/\n$//o;
	#$self->status("read line $lineCount:$line");

	# end is line consisting of only '-'
	last if ( $line=~m/^\-\-\-\-\-\-\-+/o );

	next if ( length($line) == 0 );

	if ( $line=~s/^([^\t]+)\t+//o ) {
	    $cur_name=$1;
	    $castNames++;

	    if ( $self->{showProgressBar} ) {
		# re-adjust target so progress bar doesn't seem too wonky
		if ( $castNames > $castCountEstimate ) {
		    $castCountEstimate = $progress->target($castNames+100);
		    $next_update=$progress->update($castNames);
		}
		elsif ( $castNames > $next_update ) {
		    $next_update=$progress->update($castNames);
		}
	    }
	}

	my $billing;
	my $HostNarrator="";
	if ( $whatAreWeParsing < 3 ) {
	    # actors or actresses
	    $billing="9999";
	    if ( $line=~s/\s*<(\d+)>//o ) {
		$billing=sprintf("%04d", int($1));
	    }

	    if ( (my $start=index($line, " [")) != -1 ) {
		#my $end=rindex($line, "]");
		my $ex=substr($line, $start+1);

		if ( $ex=~s/Host//o ) {
		    if ( length($HostNarrator) ) {
			$HostNarrator.=",";
		    }
		    $HostNarrator.="Host";
		}
		if ( $ex=~s/Narrator//o ) {
		    if ( length($HostNarrator) ) {
			$HostNarrator.=",";
		    }
		    $HostNarrator.="Narrator";
		}
		$line=substr($line, 0, $start);
		# ignore character name
	    }
	}
	# try ignoring these
	next if ($line=~m/\s*\{\{SUSPENDED\}\}/o);

	# don't see what these are...?
	# ignore {{SUSPENDED}}
	$line=~s/\s*\{\{SUSPENDED\}\}//o;

  # [honir] this is wrong - this puts cast from all the episodes as though they are in the entire series!
	# ##ignore {Twelve Angry Men (1954)}
	$line=~s/\s*\{[^\}]+\}//o;

	if ( $whatAreWeParsing < 3 ) {
	    if ( $line=~s/\s*\(aka ([^\)]+)\).*$//o ) {
		# $attr=$1;
	    }
	}
	if ( $line=~s/  (\(.*)$//o ) {
	    # $attrs=$1;
	}
	$line=~s/^\s+//og;
	$line=~s/\s+$//og;

	if ( $whatAreWeParsing < 3 ) {
	    if ( $line=~s/\s+Narrator$//o ) {
		# ignore
	    }
	}

	my $val=$self->{movies}{$line};
	my $name=$cur_name;
	if ( length($HostNarrator) ) {
	    $name.="[$HostNarrator]";
	}
	if ( defined($billing) ) {
	    if ( defined($val) ) {
		$self->{movies}{$line}=$val."|$billing:$name";
	    }
	    else {
		$self->{movies}{$line}="$billing:$name";
	    }
	}
	else {
	    if ( defined($val) ) {
		$self->{movies}{$line}=$val."|$name";
	    }
	    else {
		$self->{movies}{$line}=$name;
	    }
	}
	$count++;
    }
    $progress->update($castCountEstimate) if ($self->{showProgressBar});

    $self->status(sprintf("parsing $whichCastOrDirector found ".withThousands($castNames)." names, ".
			  withThousands($count)." titles in ".withThousands($lineCount)." lines in %d seconds",time()-$startTime));

    closeMaybeGunzip($file, $fh);

    return($castNames);
}

sub readRatings($$$$)
{
    my ($self, $countEstimate, $file)=@_;
    my $startTime=time();
    my $lineCount=0;

    my $fh = openMaybeGunzip($file) || return(-2);
    while(<$fh>) {
	$lineCount++;
	if ( m/^MOVIE RATINGS REPORT/o ) {
	    if ( !($_=<$fh>) || !m/^\s*$/o) {
		$self->error("missing empty line after \"MOVIE RATINGS REPORT\" at line $lineCount");
		closeMaybeGunzip($file, $fh);
		return(-1);
	    }
	    if ( !($_=<$fh>) || !m/^New  Distribution  Votes  Rank  Title/o ) {
		$self->error("missing \"New  Distribution  Votes  Rank  Title\" at line $lineCount");
		closeMaybeGunzip($file, $fh);
		return(-1);
	    }
	    last;
	}
	elsif ( $lineCount > 1000 ) {
	    $self->error("$file: stopping at line $lineCount, didn't see \"MOVIE RATINGS REPORT\" line");
	    closeMaybeGunzip($file, $fh);
	    return(-1);
	}
    }

    my $progress=Term::ProgressBar->new({name  => "parsing Ratings",
					 count => $countEstimate,
					 ETA   => 'linear'})
      if ($self->{showProgressBar});

    $progress->minor(0) if ($self->{showProgressBar});
    $progress->max_update_rate(1) if ($self->{showProgressBar});
    my $next_update=0;

    my $count=0;
    while(<$fh>) {
	$lineCount++;
	my $line=$_;
	#print "read line $lineCount:$line";

	$line=~s/\n$//o;

	# skip empty lines (only really appear right before last line ending with ----
	next if ( $line=~m/^\s*$/o );
	# end is line consisting of only '-'
	last if ( $line=~m/^\-\-\-\-\-\-\-+/o );

        # e.g. New  Distribution  Votes  Rank  Title
        #            0000000133  225568   8.9  12 Angry Men (1957)
	if ( $line=~s/^\s+([\.|\*|\d]+)\s+(\d+)\s+(\d+)\.(\d+)\s+//o ) {
	    $self->{movies}{$line}=[$1,$2,"$3.$4"];
	    $count++;
	    if ( $self->{showProgressBar} ) {
		# re-adjust target so progress bar doesn't seem too wonky
		if ( $count > $countEstimate ) {
		    $countEstimate = $progress->target($count+1000);
		    $next_update=$progress->update($count);
		}
		elsif ( $count > $next_update ) {
		    $next_update=$progress->update($count);
		}
	    }
	}
	else {
	    $self->error("$file:$lineCount: unrecognized format");
	    $next_update=$progress->update($count) if ($self->{showProgressBar});
	}
    }
    $progress->update($countEstimate) if ($self->{showProgressBar});

    $self->status(sprintf("parsing Ratings found ".withThousands($count)." titles in ".
			  withThousands($lineCount)." lines in %d seconds",time()-$startTime));

    closeMaybeGunzip($file, $fh);
    return($count);
}

sub readKeywords($$$$)
{
    my ($self, $countEstimate, $file)=@_;
    my $startTime=time();
    my $lineCount=0;

    my $fh = openMaybeGunzip($file) || return(-2);
    while(<$fh>) {
	$lineCount++;

	if ( m/THE KEYWORDS LIST/ ) {
	    if ( !($_=<$fh>) || !m/^===========/o ) {
		$self->error("missing ======= after \"THE KEYWORDS LIST\" at line $lineCount");
		closeMaybeGunzip($file, $fh);
		return(-1);
	    }
	    if ( !($_=<$fh>) || !m/^\s*$/o ) {
		$self->error("missing empty line after ======= at line $lineCount");
		closeMaybeGunzip($file, $fh);
		return(-1);
	    }
	    last;
	}
	elsif ( $lineCount > 100000 ) {
	    $self->error("$file: stopping at line $lineCount, didn't see \"THE KEYWORDS LIST\" line");
	    closeMaybeGunzip($file, $fh);
	    return(-1);
	}
    }

    my $progress=Term::ProgressBar->new({name  => "parsing keywords",
					 count => $countEstimate,
					 ETA   => 'linear'})
      if ($self->{showProgressBar});

    $progress->minor(0) if ($self->{showProgressBar});
    $progress->max_update_rate(1) if ($self->{showProgressBar});
    my $next_update=0;

    my $count=0;
    while(<$fh>) {
	$lineCount++;
	my $line=$_;
	chomp($line);
	next if ($line =~ m/^\s*$/);
	my ($title, $keyword) = ($line =~ m/^(.*)\s+(\S+)\s*$/);
	if ( defined($title) and defined($keyword) ) {

            my ($episode) = $title =~ m/^.*\s+(\{.*\})$/;

            # ignore anything which is an episode (e.g. "{Doctor Who (#10.22)}" )
            if ( !defined $episode || $episode eq '' )
            {
                if ( defined($self->{movies}{$title}) ) {
                    $self->{movies}{$title}.=",".$keyword;
                } else {
                    $self->{movies}{$title}=$keyword;
                    # returned count is number of unique titles found
                    $count++;
                }
            }

            if ( $self->{showProgressBar} ) {
                # re-adjust target so progress bar doesn't seem too wonky
    	        if ( $count > $countEstimate ) {
    	    	    $countEstimate = $progress->target($count+1000);
                    $next_update=$progress->update($count);
    	        }
    	        elsif ( $count > $next_update ) {
    	    	    $next_update=$progress->update($count);
    	        }
    	    }
        } else {
	    $self->error("$file:$lineCount: unrecognized format \"$line\"");
	    $next_update=$progress->update($count) if ($self->{showProgressBar});
	}
    }
    $progress->update($countEstimate) if ($self->{showProgressBar});

    $self->status(sprintf("parsing Keywords found ".withThousands($count)." titles in ".
			  withThousands($lineCount)." lines in %d seconds",time()-$startTime));

    closeMaybeGunzip($file, $fh);
    return($count);
}

sub readPlots($$$$)
{
    my ($self, $countEstimate, $file)=@_;
    my $startTime=time();
    my $lineCount=0;

    my $fh = openMaybeGunzip($file) || return(-2);
    while(<$fh>) {
	$lineCount++;

	if ( m/PLOT SUMMARIES LIST/ ) {
	    if ( !($_=<$fh>) || !m/^===========/o ) {
		$self->error("missing ======= after \"PLOT SUMMARIES LIST\" at line $lineCount");
		closeMaybeGunzip($file, $fh);
		return(-1);
	    }
	    if ( !($_=<$fh>) || !m/^-----------/o ) {
		$self->error("missing ------- line after ======= at line $lineCount");
		closeMaybeGunzip($file, $fh);
		return(-1);
	    }
	    last;
	}
	elsif ( $lineCount > 500 ) {
	    $self->error("$file: stopping at line $lineCount, didn't see \"PLOT SUMMARIES LIST\" line");
	    closeMaybeGunzip($file, $fh);
	    return(-1);
	}
    }

    my $progress=Term::ProgressBar->new({name  => "parsing plots",
					 count => $countEstimate,
					 ETA   => 'linear'})
      if ($self->{showProgressBar});

    $progress->minor(0) if ($self->{showProgressBar});
    $progress->max_update_rate(1) if ($self->{showProgressBar});
    my $next_update=0;

    my $count=0;
    while(<$fh>) {
	$lineCount++;
	my $line=$_;
	chomp($line);
	next if ($line =~ m/^\s*$/);
	my ($title, $episode) = ($line =~ m/^MV:\s(.*?)\s?(\{.*\})?$/);
	if ( defined($title) ) {

            # ignore anything which is an episode (e.g. "{Doctor Who (#10.22)}" )
            if ( !defined $episode || $episode eq '' )
            {
                my $plot = '';
                LOOP:
                while (1) {
                    if ( $line = <$fh> ) {
                        $lineCount++;
                        chomp($line);
                        next if ($line =~ m/^\s*$/);
                        if ( $line =~ m/PL:\s(.*)$/ ) {     # plot summary is a number of lines starting "PL:"
                            $plot .= ($plot ne ''?' ':'') . $1;
                        }
                        last LOOP if ( $line =~ m/BY:\s(.*)$/ );     # the author line "BY:" signals the end of the plot summary
                    } else {
                        last LOOP;
                    }
                }

                if ( !defined($self->{movies}{$title}) ) {
                    # ensure there's no tab chars in the plot or else the db stage will barf
                    $plot =~ s/\t//og;
                    $self->{movies}{$title}=$plot;
                    # returned count is number of unique titles found
                    $count++;
                }
            }

            if ( $self->{showProgressBar} ) {
                # re-adjust target so progress bar doesn't seem too wonky
    	        if ( $count > $countEstimate ) {
    	    	    $countEstimate = $progress->target($count+1000);
                    $next_update=$progress->update($count);
    	        }
    	        elsif ( $count > $next_update ) {
    	    	    $next_update=$progress->update($count);
    	        }
    	    }
        } else {
            # skip lines up to the next "MV:"
            if ($line !~ m/^(---|PL:|BY:)/ ) {
                $self->error("$file:$lineCount: unrecognized format \"$line\"");
            }
	    $next_update=$progress->update($count) if ($self->{showProgressBar});
	}
    }
    $progress->update($countEstimate) if ($self->{showProgressBar});

    $self->status(sprintf("parsing Plots found $count ".withThousands($count)." in ".
			  withThousands($lineCount)." lines in %d seconds",time()-$startTime));

    closeMaybeGunzip($file, $fh);
    return($count);
}

sub stageComplete($)
{
    my ($self, $stage)=@_;

    if ( -f "$self->{imdbDir}/stage$stage.data" ) {
	return(1);
    }
    return(0);
}

sub dbinfoLoad($)
{
    my $self=shift;

    my $ret=XMLTV::IMDB::loadDBInfo($self->{moviedbInfo});
    if ( ref $ret eq 'SCALAR' ) {
	return($ret);
    }
    $self->{dbinfo}=$ret;
    return(undef);
}

sub dbinfoAdd($$$)
{
    my ($self, $key, $value)=@_;
    $self->{dbinfo}->{$key}=$value;
}

sub dbinfoGet($$$)
{
    my ($self, $key, $defaultValue)=@_;
    if ( defined($self->{dbinfo}->{$key}) ) {
	return($self->{dbinfo}->{$key});
    }
    return($defaultValue);
}

sub dbinfoSave($)
{
    my $self=shift;
    open(INFO, "> $self->{moviedbInfo}") || return(1);
    for (sort keys %{$self->{dbinfo}}) {
	print INFO "".$_.":".$self->{dbinfo}->{$_}."\n";
    }
    close(INFO);
    return(0);
}

sub dbinfoGetFileSize($$)
{
    my ($self, $key)=@_;

    if ( !defined($self->{imdbListFiles}->{$key}) ) {
	die ("invalid call");
    }
    my $fileSize=int(-s "$self->{imdbListFiles}->{$key}");

    # if compressed, then attempt to run gzip -l
    if ( $self->{imdbListFiles}->{$key}=~m/.gz$/) {
	if ( open(my $fd, "gzip -l ".$self->{imdbListFiles}->{$key}."|") ) {
	    # if parse fails, then defalt to wild ass guess of compression of 65%
	    $fileSize=int(($fileSize*100)/(100-65));

	    while(<$fd>) {
		if ( m/^\s*\d+\s+(\d+)/ ) {
		    $fileSize=$1;
		}
	    }
	    close($fd);
	}
	else {
	    # wild ass guess of compression of 65%
	    $fileSize=int(($fileSize*100)/(100-65));
	}
    }
    return($fileSize);
}

sub dbinfoCalcEstimate($$$)
{
    my ($self, $key, $estimateSizePerEntry)=@_;

    my $fileSize=$self->dbinfoGetFileSize($key);

    my $countEstimate=int($fileSize/$estimateSizePerEntry);

    $self->dbinfoAdd($key."_list_file", $self->{imdbListFiles}->{$key});
    $self->dbinfoAdd($key."_list_file_size", int(-s "$self->{imdbListFiles}->{$key}"));
    $self->dbinfoAdd($key."_list_file_size_uncompressed", $fileSize);
    $self->dbinfoAdd($key."_list_count_estimate", $countEstimate);
    return($countEstimate);
}

sub dbinfoCalcBytesPerEntry($$$)
{
    my ($self, $key, $calcActualForThisNumber)=@_;

    my $fileSize=$self->dbinfoGetFileSize($key);

    return(int($fileSize/$calcActualForThisNumber));
}

sub invokeStage($$)
{
    my ($self, $stage)=@_;

    my $startTime=time();
    if ( $stage == 1 ) {
	$self->status("parsing Movies list for stage $stage..");
	my $countEstimate=$self->dbinfoCalcEstimate("movies", 47);

	my $num=$self->readMoviesOrGenres("Movies", $countEstimate, "$self->{imdbListFiles}->{movies}");
	if ( $num < 0 ) {
	    if ( $num == -2 ) {
		$self->error("you need to download $self->{imdbListFiles}->{movies} from ftp.imdb.com");
	    }
	    return(1);
	}
	elsif ( abs($num - $countEstimate) > $countEstimate*.10 ) {
	    my $better=$self->dbinfoCalcBytesPerEntry("movies", $num);
	    $self->status("ARG estimate of $countEstimate for movies needs updating, found $num ($better bytes/entry)");
	}
	$self->dbinfoAdd("db_stat_movie_count", "$num");

	$self->status("writing stage1 data ..");
	{
	    my $countEstimate=$self->dbinfoGet("db_stat_movie_count", 0);
	    my $progress=Term::ProgressBar->new({name  => "writing titles",
						 count => $countEstimate,
						 ETA   => 'linear'})
	      if ($self->{showProgressBar});
	    $progress->minor(0) if ($self->{showProgressBar});
	    $progress->max_update_rate(1) if ($self->{showProgressBar});
	    my $next_update=0;

	    open(OUT, "> $self->{imdbDir}/stage$stage.data") || die "$self->{imdbDir}/stage$stage.data:$!";
	    my $count=0;
	    for my $movie (@{$self->{movies}}) {
		print OUT "$movie\n";

		$count++;
		if ($self->{showProgressBar}) {
		    # re-adjust target so progress bar doesn't seem too wonky
		    if ( $count > $countEstimate ) {
			$countEstimate = $progress->target($count+100);
			$next_update=$progress->update($count);
		    }
		    elsif ( $count > $next_update ) {
			$next_update=$progress->update($count);
		    }
		}
	    }
	    $progress->update($countEstimate) if ($self->{showProgressBar});
	    close(OUT);
	    delete($self->{movies});
	}
    }
    elsif ( $stage == 2 ) {
	$self->status("parsing Directors list for stage $stage..");

	my $countEstimate=$self->dbinfoCalcEstimate("directors", 258);

	my $num=$self->readCastOrDirectors("Directors", $countEstimate, "$self->{imdbListFiles}->{directors}");
	if ( $num < 0 ) {
	    if ( $num == -2 ) {
		$self->error("you need to download $self->{imdbListFiles}->{directors} from ftp.imdb.com (see http://www.imdb.com/interfaces)");
	    }
	    return(1);
	}
	elsif ( abs($num - $countEstimate) > $countEstimate*.10 ) {
	    my $better=$self->dbinfoCalcBytesPerEntry("directors", $num);
	    $self->status("ARG estimate of $countEstimate for directors needs updating, found $num ($better bytes/entry)");
	}
	$self->dbinfoAdd("db_stat_director_count", "$num");

	$self->status("writing stage2 data ..");
	{
	    my $countEstimate=$self->dbinfoGet("db_stat_movie_count", 0);
	    my $progress=Term::ProgressBar->new({name  => "writing directors",
						 count => $countEstimate,
						 ETA   => 'linear'})
	      if ($self->{showProgressBar});
	    $progress->minor(0) if ($self->{showProgressBar});
	    $progress->max_update_rate(1) if ($self->{showProgressBar});
	    my $next_update=0;

	    my $count=0;
	    open(OUT, "> $self->{imdbDir}/stage$stage.data") || die "$self->{imdbDir}/stage$stage.data:$!";
	    for my $key (keys %{$self->{movies}}) {
		my %dir;
		for (split('\|', $self->{movies}{$key})) {
		    $dir{$_}++;
		}
		my @list;
		for (keys %dir) {
		    push(@list, sprintf("%03d:%s", $dir{$_}, $_));
		}
		my $value="";
		for my $c (reverse sort {$a cmp $b} @list) {
		    my ($num, $name)=split(':', $c);
		    $value.=$name."|";
		}
		$value=~s/\|$//o;
		print OUT "$key\t$value\n";

		$count++;
		if ($self->{showProgressBar}) {
		    # re-adjust target so progress bar doesn't seem too wonky
		    if ( $count > $countEstimate ) {
			$countEstimate = $progress->target($count+100);
			$next_update=$progress->update($count);
		    }
		    elsif ( $count > $next_update ) {
			$next_update=$progress->update($count);
		    }
		}
	    }
	    $progress->update($countEstimate) if ($self->{showProgressBar});
	    close(OUT);
	    delete($self->{movies});
	}
	#unlink("$self->{imdbDir}/stage1.data");
    }
    elsif ( $stage == 3 ) {
	$self->status("parsing Actors list for stage $stage..");

	#print "re-reading movies into memory for reverse lookup..\n";
	my $countEstimate=$self->dbinfoCalcEstimate("actors", 449);

	my $num=$self->readCastOrDirectors("Actors", $countEstimate, "$self->{imdbListFiles}->{actors}");
	if ( $num < 0 ) {
	    if ( $num == -2 ) {
		$self->error("you need to download $self->{imdbListFiles}->{actors} from ftp.imdb.com (see http://www.imdb.com/interfaces)");
	    }
	    return(1);
	}
	elsif ( abs($num - $countEstimate) > $countEstimate*.10 ) {
	    my $better=$self->dbinfoCalcBytesPerEntry("actors", $num);
	    $self->status("ARG estimate of $countEstimate for actors needs updating, found $num ($better bytes/entry)");
	}
	$self->dbinfoAdd("db_stat_actor_count", "$num");

	$self->status("writing stage3 data ..");
	{
	    my $countEstimate=$self->dbinfoGet("db_stat_movie_count", 0);
	    my $progress=Term::ProgressBar->new({name  => "writing actors",
						 count => $countEstimate,
						 ETA   => 'linear'})
	      if ($self->{showProgressBar});
	    $progress->minor(0) if ($self->{showProgressBar});
	    $progress->max_update_rate(1) if ($self->{showProgressBar});
	    my $next_update=0;

	    my $count=0;
	    open(OUT, "> $self->{imdbDir}/stage$stage.data") || die "$self->{imdbDir}/stage$stage.data:$!";
	    for my $key (keys %{$self->{movies}}) {
		print OUT "$key\t$self->{movies}{$key}\n";

		$count++;
		if ($self->{showProgressBar}) {
		    # re-adjust target so progress bar doesn't seem too wonky
		    if ( $count > $countEstimate ) {
			$countEstimate = $progress->target($count+100);
			$next_update=$progress->update($count);
		    }
		    elsif ( $count > $next_update ) {
			$next_update=$progress->update($count);
		    }
		}
	    }
	    $progress->update($countEstimate) if ($self->{showProgressBar});
	    close(OUT);
	    delete($self->{movies});
	}
    }
    elsif ( $stage == 4 ) {
	$self->status("parsing Actresses list for stage $stage..");

	my $countEstimate=$self->dbinfoCalcEstimate("actresses", 483);
	my $num=$self->readCastOrDirectors("Actresses", $countEstimate, "$self->{imdbListFiles}->{actresses}");
	if ( $num < 0 ) {
	    if ( $num == -2 ) {
		$self->error("you need to download $self->{imdbListFiles}->{actresses} from ftp.imdb.com (see http://www.imdb.com/interfaces)");
	    }
	    return(1);
	}
	elsif ( abs($num - $countEstimate) > $countEstimate*.10 ) {
	    my $better=$self->dbinfoCalcBytesPerEntry("actresses", $num);
	    $self->status("ARG estimate of $countEstimate for actresses needs updating, found $num ($better bytes/entry)");
	}
	$self->dbinfoAdd("db_stat_actress_count", "$num");

	$self->status("writing stage4 data ..");
	{
	    my $countEstimate=$self->dbinfoGet("db_stat_movie_count", 0);
	    my $progress=Term::ProgressBar->new({name  => "writing actresses",
						 count => $countEstimate,
						 ETA   => 'linear'})
	      if ($self->{showProgressBar});
	    $progress->minor(0) if ($self->{showProgressBar});
	    $progress->max_update_rate(1) if ($self->{showProgressBar});
	    my $next_update=0;

	    my $count=0;
	    open(OUT, "> $self->{imdbDir}/stage$stage.data") || die "$self->{imdbDir}/stage$stage.data:$!";
	    for my $key (keys %{$self->{movies}}) {
		print OUT "$key\t$self->{movies}{$key}\n";
		$count++;
		if ($self->{showProgressBar}) {
		    # re-adjust target so progress bar doesn't seem too wonky
		    if ( $count > $countEstimate ) {
			$countEstimate = $progress->target($count+100);
			$next_update=$progress->update($count);
		    }
		    elsif ( $count > $next_update ) {
			$next_update=$progress->update($count);
		    }
		}
	    }
	    $progress->update($countEstimate) if ($self->{showProgressBar});
	    close(OUT);
	    delete($self->{movies});
	}
	#unlink("$self->{imdbDir}/stage3.data");
    }
    elsif ( $stage == 5 ) {
	$self->status("parsing Genres list for stage $stage..");
	my $countEstimate=$self->dbinfoCalcEstimate("genres", 68);

	my $num=$self->readMoviesOrGenres("Genres", $countEstimate, "$self->{imdbListFiles}->{genres}");
	if ( $num < 0 ) {
	    if ( $num == -2 ) {
		$self->error("you need to download $self->{imdbListFiles}->{genres} from ftp.imdb.com");
	    }
	    return(1);
	}
	elsif ( abs($num - $countEstimate) > $countEstimate*.10 ) {
	    my $better=$self->dbinfoCalcBytesPerEntry("genres", $num);
	    $self->status("ARG estimate of $countEstimate for genres needs updating, found $num ($better bytes/entry)");
	}
	$self->dbinfoAdd("db_stat_genres_count", "$num");

	$self->status("writing stage5 data ..");
	{
	    my $countEstimate=$self->dbinfoGet("db_stat_genres_count", 0);
	    my $progress=Term::ProgressBar->new({name  => "writing genres",
						 count => $countEstimate,
						 ETA   => 'linear'})
	      if ($self->{showProgressBar});
	    $progress->minor(0) if ($self->{showProgressBar});
	    $progress->max_update_rate(1) if ($self->{showProgressBar});
	    my $next_update=0;

	    open(OUT, "> $self->{imdbDir}/stage$stage.data") || die "$self->{imdbDir}/stage$stage.data:$!";
	    my $count=0;
	    for my $movie (keys %{$self->{movies}}) {
		print OUT "$movie\t$self->{movies}->{$movie}\n";

		$count++;
		if ($self->{showProgressBar}) {
		    # re-adjust target so progress bar doesn't seem too wonky
		    if ( $count > $countEstimate ) {
			$countEstimate = $progress->target($count+100);
			$next_update=$progress->update($count);
		    }
		    elsif ( $count > $next_update ) {
			$next_update=$progress->update($count);
		    }
		}
	    }
	    $progress->update($countEstimate) if ($self->{showProgressBar});
	    close(OUT);
	    delete($self->{movies});
	}
    }
    elsif ( $stage == 6 ) {
	$self->status("parsing Ratings list for stage $stage..");
	my $countEstimate=$self->dbinfoCalcEstimate("ratings", 68);

	my $num=$self->readRatings($countEstimate, "$self->{imdbListFiles}->{ratings}");
	if ( $num < 0 ) {
	    if ( $num == -2 ) {
		$self->error("you need to download $self->{imdbListFiles}->{ratings} from ftp.imdb.com");
	    }
	    return(1);
	}
	elsif ( abs($num - $countEstimate) > $countEstimate*.10 ) {
	    my $better=$self->dbinfoCalcBytesPerEntry("ratings", $num);
	    $self->status("ARG estimate of $countEstimate for ratings needs updating, found $num ($better bytes/entry)");
	}
	$self->dbinfoAdd("db_stat_ratings_count", "$num");

	$self->status("writing stage6 data ..");
	{
	    my $countEstimate=$self->dbinfoGet("db_stat_ratings_count", 0);
	    my $progress=Term::ProgressBar->new({name  => "writing ratings",
						 count => $countEstimate,
						 ETA   => 'linear'})
	      if ($self->{showProgressBar});
	    $progress->minor(0) if ($self->{showProgressBar});
	    $progress->max_update_rate(1) if ($self->{showProgressBar});
	    my $next_update=0;

	    open(OUT, "> $self->{imdbDir}/stage$stage.data") || die "$self->{imdbDir}/stage$stage.data:$!";
	    my $count=0;
	    for my $movie (keys %{$self->{movies}}) {
		my @value=@{$self->{movies}->{$movie}};
		print OUT "$movie\t$value[0]\t$value[1]\t$value[2]\n";

		$count++;
		if ($self->{showProgressBar}) {
		    # re-adjust target so progress bar doesn't seem too wonky
		    if ( $count > $countEstimate ) {
			$countEstimate = $progress->target($count+100);
			$next_update=$progress->update($count);
		    }
		    elsif ( $count > $next_update ) {
			$next_update=$progress->update($count);
		    }
		}
	    }
	    $progress->update($countEstimate) if ($self->{showProgressBar});
	    close(OUT);
	    delete($self->{movies});
	}
    }
    elsif ( $stage == 7 ) {
	$self->status("parsing Keywords list for stage $stage..");

	if ( !defined($self->{imdbListFiles}->{keywords}) ) {
	    $self->status("no keywords file downloaded, see --with-keywords details in documentation");
	    return(0);
	}

	my $countEstimate=5630000;
	my $num=$self->readKeywords($countEstimate, "$self->{imdbListFiles}->{keywords}");
	if ( $num < 0 ) {
	    if ( $num == -2 ) {
		$self->error("you need to download $self->{imdbListFiles}->{keywords} from ftp.imdb.com");
	    }
	    return(1);
	}
	elsif ( abs($num - $countEstimate) > $countEstimate*.05 ) {
	    $self->status("ARG estimate of $countEstimate for keywords needs updating, found $num");
	}
	$self->dbinfoAdd("keywords_list_file",         "$self->{imdbListFiles}->{keywords}");
	$self->dbinfoAdd("keywords_list_file_size", -s "$self->{imdbListFiles}->{keywords}");
	$self->dbinfoAdd("db_stat_keywords_count", "$num");

	$self->status("writing stage$stage data ..");
	{
	    my $countEstimate=$self->dbinfoGet("db_stat_keywords_count", 0);
	    my $progress=Term::ProgressBar->new({name  => "writing keywords",
						 count => $countEstimate,
						 ETA   => 'linear'})
	      if ($self->{showProgressBar});
	    $progress->minor(0) if ($self->{showProgressBar});
	    $progress->max_update_rate(1) if ($self->{showProgressBar});
	    my $next_update=0;

	    open(OUT, "> $self->{imdbDir}/stage$stage.data") || die "$self->{imdbDir}/stage$stage.data:$!";

	    my $count=0;
	    for my $movie (keys %{$self->{movies}}) {
		print OUT "$movie\t$self->{movies}->{$movie}\n";

		$count++;
		if ($self->{showProgressBar}) {
		    # re-adjust target so progress bar doesn't seem too wonky
		    if ( $count > $countEstimate ) {
			$countEstimate = $progress->target($count+100);
			$next_update=$progress->update($count);
		    }
		    elsif ( $count > $next_update ) {
			$next_update=$progress->update($count);
		    }
		}
	    }
	    $progress->update($countEstimate) if ($self->{showProgressBar});
	    close(OUT);
	    delete($self->{movies});
	}
    }
    elsif ( $stage == 8 ) {
	$self->status("parsing Plot list for stage $stage..");

	if ( !defined($self->{imdbListFiles}->{plot}) ) {
	    $self->status("no plot file downloaded, see --with-plot details in documentation");
	    return(0);
	}

	my $countEstimate=222222;
	my $num=$self->readPlots($countEstimate, "$self->{imdbListFiles}->{plot}");
	if ( $num < 0 ) {
	    if ( $num == -2 ) {
		$self->error("you need to download $self->{imdbListFiles}->{plot} from ftp.imdb.com");
	    }
	    return(1);
	}
	elsif ( abs($num - $countEstimate) > $countEstimate*.05 ) {
	    $self->status("ARG estimate of $countEstimate for plots needs updating, found $num");
	}
	$self->dbinfoAdd("plots_list_file",         "$self->{imdbListFiles}->{plot}");
	$self->dbinfoAdd("plots_list_file_size", -s "$self->{imdbListFiles}->{plot}");
	$self->dbinfoAdd("db_stat_plots_count", "$num");

	$self->status("writing stage$stage data ..");
	{
	    my $countEstimate=$self->dbinfoGet("db_stat_plots_count", 0);
	    my $progress=Term::ProgressBar->new({name  => "writing plots",
						 count => $countEstimate,
						 ETA   => 'linear'})
	      if ($self->{showProgressBar});
	    $progress->minor(0) if ($self->{showProgressBar});
	    $progress->max_update_rate(1) if ($self->{showProgressBar});
	    my $next_update=0;

	    open(OUT, "> $self->{imdbDir}/stage$stage.data") || die "$self->{imdbDir}/stage$stage.data:$!";

	    my $count=0;
	    for my $movie (keys %{$self->{movies}}) {
		print OUT "$movie\t$self->{movies}->{$movie}\n";

		$count++;
		if ($self->{showProgressBar}) {
		    # re-adjust target so progress bar doesn't seem too wonky
		    if ( $count > $countEstimate ) {
			$countEstimate = $progress->target($count+100);
			$next_update=$progress->update($count);
		    }
		    elsif ( $count > $next_update ) {
			$next_update=$progress->update($count);
		    }
		}
	    }
	    $progress->update($countEstimate) if ($self->{showProgressBar});
	    close(OUT);
	    delete($self->{movies});
	}
    }
    elsif ( $stage == $self->{stageLast} ) {
	my $tab=sprintf("\t");

	$self->status("indexing all previous stage's data for stage ".$self->{stageLast}."..");

	$self->status("parsing stage 1 data (movie list)..");
	my %movies;
	{
	    my $countEstimate=$self->dbinfoGet("db_stat_movie_count", 0);
	    my $progress=Term::ProgressBar->new({name  => "reading titles",
						 count => $countEstimate,
						 ETA   => 'linear'})
	      if ($self->{showProgressBar});
	    $progress->minor(0) if ($self->{showProgressBar});
	    $progress->max_update_rate(1) if ($self->{showProgressBar});
	    my $next_update=0;

	    open(IN, "< $self->{imdbDir}/stage1.data") || die "$self->{imdbDir}/stage1.data:$!";
	    while(<IN>) {
		chop();
		$movies{$_}="";

		if ($self->{showProgressBar}) {
		    # re-adjust target so progress bar doesn't seem too wonky
		    if ( $. > $countEstimate ) {
			$countEstimate = $progress->target($.+100);
			$next_update=$progress->update($.);
		    }
		    elsif ( $. > $next_update ) {
			$next_update=$progress->update($.);
		    }
		}
	    }
	    close(IN);
	    $progress->update($countEstimate) if ($self->{showProgressBar});
	}

	$self->status("merging in stage 2 data (directors)..");
	if ( 1 ) {
	    my $countEstimate=$self->dbinfoGet("db_stat_movie_count", 0);
	    my $progress=Term::ProgressBar->new({name  => "merging directors",
						 count => $countEstimate,
						 ETA   => 'linear'})
	      if ($self->{showProgressBar});
	    $progress->minor(0) if ($self->{showProgressBar});
	    $progress->max_update_rate(1) if ($self->{showProgressBar});
	    my $next_update=0;

	    open(IN, "< $self->{imdbDir}/stage2.data") || die "$self->{imdbDir}/stage2.data:$!";
	    while(<IN>) {
		chop();
		s/^([^\t]+)\t//o;
		if ( !defined($movies{$1}) ) {
		    $self->error("directors list references unidentified title '$1'");
		    next;
		}
		$movies{$1}=$_;

		if ($self->{showProgressBar}) {
		    # re-adjust target so progress bar doesn't seem too wonky
		    if ( $. > $countEstimate ) {
			$countEstimate = $progress->target($.+100);
			$next_update=$progress->update($.);
		    }
		    elsif ( $. > $next_update ) {
			$next_update=$progress->update($.);
		    }
		}
	    }
	    $progress->update($countEstimate) if ($self->{showProgressBar});
	    close(IN);
	}

	if ( 1 ) {
	    # fill in default for movies we didn't have a director for
	    for my $key (keys %movies) {
		if ( !length($movies{$key})) {
		    $movies{$key}="<>";
		}
	    }
	}

	$self->status("merging in stage 3 data (actors)..");
	if ( 1 ) {
	    my $countEstimate=$self->dbinfoGet("db_stat_movie_count", 0);
	    my $progress=Term::ProgressBar->new({name  => "merging actors",
						 count => $countEstimate,
						 ETA   => 'linear'})
	      if ($self->{showProgressBar});
	    $progress->minor(0) if ($self->{showProgressBar});
	    $progress->max_update_rate(1) if ($self->{showProgressBar});
	    my $next_update=0;

	    open(IN, "< $self->{imdbDir}/stage3.data") || die "$self->{imdbDir}/stage3.data:$!";
	    while(<IN>) {
		chop();
		s/^([^\t]+)\t//o;
		my $dbkey=$1;
		my $val=$movies{$dbkey};
		if ( !defined($val) ) {
		    $self->error("actors list references unidentified title '$dbkey'");
		    next;
		}
		if ( $val=~m/$tab/o ) {
		    $movies{$dbkey}=$val."|".$_;
		}
		else {
		    $movies{$dbkey}=$val.$tab.$_;
		}
		if ($self->{showProgressBar}) {
		    # re-adjust target so progress bar doesn't seem too wonky
		    if ( $. > $countEstimate ) {
			$countEstimate = $progress->target($.+100);
			$next_update=$progress->update($.);
		    }
		    elsif ( $. > $next_update ) {
			$next_update=$progress->update($.);
		    }
		}
	    }
	    $progress->update($countEstimate) if ($self->{showProgressBar});
	    close(IN);
	}

	$self->status("merging in stage 4 data (actresses)..");
	if ( 1 ) {
	    my $countEstimate=$self->dbinfoGet("db_stat_movie_count", 0);
	    my $progress=Term::ProgressBar->new({name  => "merging actresses",
						 count => $countEstimate,
						 ETA   => 'linear'})
	      if ($self->{showProgressBar});
	    $progress->minor(0) if ($self->{showProgressBar});
	    $progress->max_update_rate(1) if ($self->{showProgressBar});
	    my $next_update=0;

	    open(IN, "< $self->{imdbDir}/stage4.data") || die "$self->{imdbDir}/stage4.data:$!";
	    while(<IN>) {
		chop();
		s/^([^\t]+)\t//o;
		my $dbkey=$1;
		my $val=$movies{$dbkey};
		if ( !defined($val) ) {
		    $self->error("actresses list references unidentified title '$dbkey'");
		    next;
		}
		if ( $val=~m/$tab/o ) {
		    $movies{$dbkey}=$val."|".$_;
		}
		else {
		    $movies{$dbkey}=$val.$tab.$_;
		}
		if ($self->{showProgressBar}) {
		    # re-adjust target so progress bar doesn't seem too wonky
		    if ( $. > $countEstimate ) {
			$countEstimate = $progress->target($.+100);
			$next_update=$progress->update($.);
		    }
		    elsif ( $. > $next_update ) {
			$next_update=$progress->update($.);
		    }
		}
	    }
	    $progress->update($countEstimate) if ($self->{showProgressBar});
	    close(IN);
	}
	if ( 1 ) {
	    # fill in placeholder if no actors were found
	    for my $key (keys %movies) {
		if ( !($movies{$key}=~m/$tab/o) ) {
		    $movies{$key}.=$tab."<>";
		}
	    }
	}

	$self->status("merging in stage 5 data (genres)..");
	if ( 1 ) {
	    my $countEstimate=$self->dbinfoGet("db_stat_genres_count", 1);  # '1' prevents the spurious "(nothing to do)" msg
	    my $progress=Term::ProgressBar->new({name  => "merging genres",
						 count => $countEstimate,
						 ETA   => 'linear'})
	      if ($self->{showProgressBar});
	    $progress->minor(0) if ($self->{showProgressBar});
	    $progress->max_update_rate(1) if ($self->{showProgressBar});
	    my $next_update=0;

	    open(IN, "< $self->{imdbDir}/stage5.data") || die "$self->{imdbDir}/stage5.data:$!";
	    while(<IN>) {
		chop();
		s/^([^\t]+)\t//o;
		my $dbkey=$1;
		my $genres=$_;
		my $val=$movies{$dbkey};
		if ( !defined($val) ) {
		    $self->error("genres list references unidentified title '$1'");
		    next;
		}
		$movies{$dbkey}.=$tab.$genres;

		if ($self->{showProgressBar}) {
		    # re-adjust target so progress bar doesn't seem too wonky
		    if ( $. > $countEstimate ) {
			$countEstimate = $progress->target($.+100);
			$next_update=$progress->update($.);
		    }
		    elsif ( $. > $next_update ) {
			$next_update=$progress->update($.);
		    }
		}
	    }
	    $progress->update($countEstimate) if ($self->{showProgressBar});
	    close(IN);
	}

	if ( 1 ) {
	    # fill in placeholder if no genres were found
	    for my $key (keys %movies) {
		my $val=$movies{$key};
		my $t=index($val, $tab);
		if ( $t == -1 ) {
		    die "corrupt entry '$key' '$val'";
		}
		if ( index($val, $tab, $t+1) == -1 ) {
		    $movies{$key}.=$tab."<>";
		}
	    }
	}

	$self->status("merging in stage 6 data (ratings)..");
	if ( 1 ) {
	    my $countEstimate=$self->dbinfoGet("db_stat_ratings_count", 1);  # '1' prevents the spurious "(nothing to do)" msg
	    my $progress=Term::ProgressBar->new({name  => "merging ratings",
						 count => $countEstimate,
						 ETA   => 'linear'})
	      if ($self->{showProgressBar});
	    $progress->minor(0) if ($self->{showProgressBar});
	    $progress->max_update_rate(1) if ($self->{showProgressBar});
	    my $next_update=0;

	    open(IN, "< $self->{imdbDir}/stage6.data") || die "$self->{imdbDir}/stage6.data:$!";
	    while(<IN>) {
		chop();
		s/^([^\t]+)\t([^\t]+)\t([^\t]+)\t([^\t]+)$//o;
		my $dbkey=$1;
		my ($ratingDist, $ratingVotes, $ratingRank)=($2,$3,$4);

		my $val=$movies{$dbkey};
		if ( !defined($val) ) {
		    $self->error("ratings list references unidentified title '$1'");
		    next;
		}
		$movies{$dbkey}.=$tab.$ratingDist.$tab.$ratingVotes.$tab.$ratingRank;

		if ($self->{showProgressBar}) {
		    # re-adjust target so progress bar doesn't seem too wonky
		    if ( $. > $countEstimate ) {
			$countEstimate = $progress->target($.+100);
			$next_update=$progress->update($.);
		    }
		    elsif ( $. > $next_update ) {
			$next_update=$progress->update($.);
		    }
		}
	    }
	    $progress->update($countEstimate) if ($self->{showProgressBar});
	    close(IN);
	}

	if ( 1 ) {
	    # fill in placeholder if no genres were found
	    for my $key (keys %movies) {
		my $val=$movies{$key};

		my $t=index($val, $tab);
		if ( $t == -1  ) {
		    die "corrupt entry '$key' '$val'";
		}
		my $j=index($val, $tab, $t+1);
		if ( $j == -1  ) {
		    die "corrupt entry '$key' '$val'";
		}
		if ( index($val, $tab, $j+1) == -1 ) {
		    $movies{$key}.=$tab."<>".$tab."<>".$tab."<>";
		}
	    }
	}

	$self->status("merging in stage 7 data (keywords)..");
	#if ( 1 ) {         # this stage is optional
        if ( -f "$self->{imdbDir}/stage7.data" ) {
	    my $countEstimate=$self->dbinfoGet("db_stat_keywords_count", 1);  # '1' prevents the spurious "(nothing to do)" msg
	    my $progress=Term::ProgressBar->new({name  => "merging keywords",
						 count => $countEstimate,
						 ETA   => 'linear'})
	      if ($self->{showProgressBar});
	    $progress->minor(0) if ($self->{showProgressBar});
	    $progress->max_update_rate(1) if ($self->{showProgressBar});
	    my $next_update=0;

	    open(IN, "< $self->{imdbDir}/stage7.data") || die "$self->{imdbDir}/stage7.data:$!";
	    while(<IN>) {
		chop();
		s/^([^\t]+)\t+//o;
		my $dbkey=$1;
		my $keywords=$_;
		if ( !defined($movies{$dbkey}) ) {
		    $self->error("keywords list references unidentified title '$1'");
		    next;
		}
		$movies{$dbkey}.=$tab.$keywords;

		if ($self->{showProgressBar}) {
		    # re-adjust target so progress bar doesn't seem too wonky
		    if ( $. > $countEstimate ) {
			$countEstimate = $progress->target($.+100);
			$next_update=$progress->update($.);
		    }
		    elsif ( $. > $next_update ) {
			$next_update=$progress->update($.);
		    }
		}
	    }
	    $progress->update($countEstimate) if ($self->{showProgressBar});
	    close(IN);
	}

	if ( 1 ) {
	    # fill in default for movies we didn't have any keywords for
	    for my $key (keys %movies) {
		my $val=$movies{$key};
		#keyword is 6th entry
		my $t = 0;
		for my $i (0..4) {
		    $t=index($val, $tab, $t);
		    if ( $t == -1 ) {
		    	die "Corrupt entry '$key' '$val'";
		    }
		    $t+=1;
		}
		if ( index($val, $tab, $t) == -1 ) {
		    $movies{$key}.=$tab."<>";
		}
	    }
	}

	$self->status("merging in stage 8 data (plots)..");
	#if ( 1 ) {         # this stage is optional
        if ( -f "$self->{imdbDir}/stage8.data" ) {
	    my $countEstimate=$self->dbinfoGet("db_stat_plots_count", 1);  # '1' prevents the spurious "(nothing to do)" msg
	    my $progress=Term::ProgressBar->new({name  => "merging plots",
						 count => $countEstimate,
						 ETA   => 'linear'})
	      if ($self->{showProgressBar});
	    $progress->minor(0) if ($self->{showProgressBar});
	    $progress->max_update_rate(1) if ($self->{showProgressBar});
	    my $next_update=0;

	    open(IN, "< $self->{imdbDir}/stage8.data") || die "$self->{imdbDir}/stage8.data:$!";
	    while(<IN>) {
		chop();
		s/^([^\t]+)\t+//o;
		my $dbkey=$1;
		my $plot=$_;
		if ( !defined($movies{$dbkey}) ) {
		    $self->error("plot list references unidentified title '$1'");
		    next;
		}
		$movies{$dbkey}.=$tab.$plot;

		if ($self->{showProgressBar}) {
		    # re-adjust target so progress bar doesn't seem too wonky
		    if ( $. > $countEstimate ) {
			$countEstimate = $progress->target($.+100);
			$next_update=$progress->update($.);
		    }
		    elsif ( $. > $next_update ) {
			$next_update=$progress->update($.);
		    }
		}
	    }
	    $progress->update($countEstimate) if ($self->{showProgressBar});
	    close(IN);
	}
	if ( 1 ) {
	    # fill in default for movies we didn't have any plot for
	    for my $key (keys %movies) {
		my $val=$movies{$key};
		#plot is 7th entry
		my $t = 0;
		for my $i (0..5) {
		    $t=index($val, $tab, $t);
		    if ( $t == -1 ) {
		    	die "Corrupt entry '$key' '$val'";
		    }
		    $t+=1;
		}
		if ( index($val, $tab, $t) == -1 ) {
		    $movies{$key}.=$tab."<>";
		}
	    }
	}

	#unlink("$self->{imdbDir}/stage1.data");
	#unlink("$self->{imdbDir}/stage2.data");
	#unlink("$self->{imdbDir}/stage3.data");

        # ---------------------------------------------------------------------------------------


	#
	# note: not all movies end up with a cast, but we include them anyway.
	#

	my %nmovies;
	{
	    my $countEstimate=$self->dbinfoGet("db_stat_movie_count", 0);
	    my $progress=Term::ProgressBar->new({name  => "computing index",
						 count => $countEstimate,
						 ETA   => 'linear'})
	      if ($self->{showProgressBar});
	    $progress->minor(0) if ($self->{showProgressBar});
	    $progress->max_update_rate(1) if ($self->{showProgressBar});
	    my $next_update=0;

	    my $count=0;
	    for my $key (keys %movies) {
		my $dbkey=$key;

		# drop episode information - ex: {Twelve Angry Men (1954)}
		$dbkey=~s/\s*\{[^\}]+\}//go;

		# todo - this would make things easier
		# change double-quotes around title to be (made-for-tv) suffix instead
		if ( $dbkey=~m/^\"/o && #"
		     $dbkey=~m/\"\s*\(/o ) { #"
		    $dbkey.=" (tv_series)";
		}
		# how rude, some entries have (TV) appearing more than once.
		$dbkey=~s/\(TV\)\s*\(TV\)$/(TV)/o;

		my $qualifier;
		if ( $dbkey=~s/\s+\(TV\)$//o ) {
		    $qualifier="tv_movie";
		}
		elsif ( $dbkey=~s/\s+\(mini\) \(tv_series\)$// ) {
		    $qualifier="tv_mini_series";
		}
		elsif ( $dbkey=~s/\s+\(tv_series\)$// ) {
		    $qualifier="tv_series";
		}
		elsif ( $dbkey=~s/\s+\(mini\)$//o ) {
		    $qualifier="tv_mini_series";
		}
		elsif ( $dbkey=~s/\s+\(V\)$//o ) {
		    $qualifier="video_movie";
		}
		elsif ( $dbkey=~s/\s+\(VG\)$//o ) {
		    #$qualifier="video_game";
		    delete($movies{$key});
		    next;
		}
		else {
		    $qualifier="movie";
		}
		#if ( $dbkey=~s/\s+\((tv_series|tv_mini_series|tv_movie|video_movie|video_game)\)$//o ) {
		 #   $qualifier=$1;
		#}
		my $year;
		my $title=$dbkey;

		if ( $title=~m/^\"/o && $title=~m/\"\s*\(/o ) { #"
		    $title=~s/^\"//o; #"
		    $title=~s/\"(\s*\()/$1/o; #"
		}

		if ( $title=~s/\s+\((\d\d\d\d)\)$//o ||
		     $title=~s/\s+\((\d\d\d\d)\/[IVX]+\)$//o ) {
		    $year=$1;
		}
		elsif ( $title=~s/\s+\((\?\?\?\?)\)$//o ||
			$title=~s/\s+\((\?\?\?\?)\/[IVX]+\)$//o ) {
		    $year="0000";
		}
		else {
		    $self->error("movie list format failed to decode year from title '$title'");
		    $year="0000";
		}
		$title=~s/(.*),\s*(The|A|Une|Las|Les|Los|L\'|Le|La|El|Das|De|Het|Een)$/$2 $1/og;

		my $hashkey=lc("$title ($year)");
		$hashkey=~s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/oeg;

		if ( defined($movies{$hashkey}) ) {
		    die "unable to place moviedb key for $key, report to xmltv-devel\@lists.sf.net";
		}
		die "title \"$title\" contains a tab" if ( $title=~m/\t/o );
		#print "key:$dbkey\n\ttitle=$title\n\tyear=$year\n\tqualifier=$qualifier\n";
		#print "key $key: value=\"$movies{$key}\"\n";

		$nmovies{$hashkey}=$dbkey.$tab.$year.$tab.$qualifier.$tab.delete($movies{$key});
		$count++;

		if ($self->{showProgressBar}) {
		    # re-adjust target so progress bar doesn't seem too wonky
		    if ( $count > $countEstimate ) {
			$countEstimate = $progress->target($count+100);
			$next_update=$progress->update($count);
		    }
		    elsif ( $count > $next_update ) {
			$next_update=$progress->update($count);
		    }
		}
	    }
	    $progress->update($countEstimate) if ($self->{showProgressBar});

	    if ( scalar(keys %movies) != 0 ) {
		die "what happened, we have keys left ?";
	    }
	    undef(%movies);
	}

	{
	    my $countEstimate=$self->dbinfoGet("db_stat_movie_count", 0);
	    my $progress=Term::ProgressBar->new({name  => "writing database",
						 count => $countEstimate,
						 ETA   => 'linear'})
	      if ($self->{showProgressBar});
	    $progress->minor(0) if ($self->{showProgressBar});
	    $progress->max_update_rate(1) if ($self->{showProgressBar});
	    my $next_update=0;

	    open(IDX, "> $self->{moviedbIndex}") || die "$self->{moviedbIndex}:$!";
	    open(DAT, "> $self->{moviedbData}") || die "$self->{moviedbData}:$!";
	    my $count=0;
	    for my $key (sort {$a cmp $b} keys %nmovies) {
		my $val=delete($nmovies{$key});
		#print "movie $key: $val\n";
		#$val=~s/^([^\t]+)\t([^\t]+)\t([^\t]+)\t//o || die "internal failure ($key:$val)";
		my ($dbkey, $year, $qualifier,$directors,$actors,@rest)=split('\t', $val);
		#die ("no 1") if ( !defined($dbkey));
		#die ("no 2") if ( !defined($year));
		#die ("no 3") if ( !defined($qualifier));
		#die ("no 4") if ( !defined($directors));
		#die ("no 5") if ( !defined($actors));
		#print "key:$key\n\ttitle=$dbkey\n\tyear=$year\n\tqualifier=$qualifier\n";

		#my ($directors, $actors)=split('\t', $val);

		my $details="";

		if ( $directors eq "<>" ) {
		    $details.="<>";
		}
		else {
		    # sort directors by last name, removing duplicates
		    my $last='';
		    for my $name (sort {$a cmp $b} split('\|', $directors)) {
			if ( $name ne $last ) {
			    $details.="$name|";
			    $last=$name;
			}
		    }
		    $details=~s/\|$//o;
		}

		#print "      $dbkey: $val\n";
		if ( $actors eq "<>" ) {
		    $details.=$tab."<>";
		}
		else {
		    $details.=$tab;

		    # sort actors by billing, removing repeated entries
		    # be warned, two actors may have the same billing level
		    my $last='';
		    for my $c (sort {$a cmp $b} split('\|', $actors)) {
			my ($billing, $name)=split(':', $c);
			# remove Host/Narrators from end
			# BUG - should remove (I)'s from actors/actresses names when details are generated
			$name=~s/\s\([IVX]+\)\[/\[/o;
			$name=~s/\s\([IVX]+\)$//o;

			if ( $name ne $last ) {
			    $details.="$name|";
			    $last=$name;
			}
			#print "      $c: split gives'$billing' and '$name'\n";
		    }
		    $details=~s/\|$//o;
		}
		$count++;
		my $lineno=sprintf("%07d", $count);
		print IDX $key."\t".$dbkey."\t".$year."\t".$qualifier."\t".$lineno."\n";
		print DAT $lineno.":".$details."\t".join($tab, @rest)."\n";

		if ($self->{showProgressBar}) {
		    # re-adjust target so progress bar doesn't seem too wonky
		    if ( $count > $countEstimate ) {
			$countEstimate = $progress->target($count+100);
			$next_update=$progress->update($count);
		    }
		    elsif ( $count > $next_update ) {
			$next_update=$progress->update($count);
		    }
		}
	    }
	    $progress->update($countEstimate) if ($self->{showProgressBar});
	    close(DAT);
	    close(IDX);
	}

	$self->dbinfoAdd("db_version", $XMLTV::IMDB::VERSION);

	if ( $self->dbinfoSave() ) {
	    $self->error("$self->{moviedbInfo}:$!");
	    return(1);
	}

	$self->status("running quick sanity check on database indexes...");
	my $imdb=new XMLTV::IMDB('imdbDir' => $self->{imdbDir},
				 'verbose' => $self->{verbose});

	if ( -e "$self->{moviedbOffline}" ) {
	    unlink("$self->{moviedbOffline}");
	}

	if ( my $errline=$imdb->sanityCheckDatabase() ) {
	    open(OFF, "> $self->{moviedbOffline}") || die "$self->{moviedbOffline}:$!";
	    print OFF $errline."\n";
	    print OFF "one of the prep stages' must have produced corrupt data\n";
	    print OFF "report the following details to xmltv-devel\@lists.sf.net\n";

	    my $info=XMLTV::IMDB::loadDBInfo($self->{moviedbInfo});
	    if ( ref $info eq 'SCALAR' ) {
		print OFF "\tdbinfo file corrupt\n";
		print OFF "\t$info";
	    }
	    else {
		for my $key (sort keys %{$info}) {
		    print OFF "\t$key:$info->{$key}\n";
		}
	    }
	    print OFF "database taken offline\n";
	    close(OFF);
	    open(OFF, "< $self->{moviedbOffline}") || die "$self->{moviedbOffline}:$!";
	    while(<OFF>) {
		chop();
		$self->error($_);
	    }
	    close(OFF);
	    return(1);
	}
	$self->status("sanity intact :)");
    }
    else {
	$self->error("tv_imdb: invalid stage $stage: only 1-".$self->{stageLast}." are valid");
	return(1);
    }

    $self->dbinfoAdd("seconds_to_complete_prep_stage_$stage", (time()-$startTime));
    if ( $self->dbinfoSave() ) {
	$self->error("$self->{moviedbInfo}:$!");
	return(1);
    }
    return(0);
}

sub crunchStage($$)
{
    my ($self, $stage)=@_;

    if ( $stage == $self->{stageLast} ) {
         # check all the pre-requisite stages have been run
        for (my $st=1 ; $st < $self->{stageLast}; $st++ ) {
	if ( !$self->stageComplete($st) ) {
                    #$self->error("prep stages must be run in sequence..");
	    $self->error("prepStage $st either has never been run or failed");
                if ( grep { $_ == $st } values %{$self->{optionalStages}} ) {
                    $self->error("data for this stage will NOT be added");
                } else {
	    $self->error("rerun tv_imdb with --prepStage=$st");
	    return(1);
	}
    }
        }
    }

    if ( -f "$self->{moviedbInfo}" && $stage != 1 ) {
	my $ret=$self->dbinfoLoad();
	if ( $ret ) {
	    $self->error($ret);
	    return(1);
	}
    }

    $self->redirect("$self->{imdbDir}/stage$stage.log") || return(1);
    my $ret=$self->invokeStage($stage);
    $self->redirect(undef);

    if ( $ret == 0 ) {
	if ( $self->{errorCountInLog} == 0 ) {
	    $self->status("prep stage $stage succeeded with no errors");
	}
	else {
	    $self->status("prep stage $stage succeeded with $self->{errorCountInLog} errors in $self->{imdbDir}/stage$stage.log");
	    if ( $stage == $self->{stageLast} && $self->{errorCountInLog} > 30 && $self->{errorCountInLog} < 80 ) {
		$self->status("this stage commonly produces around 60 (or so) warnings because of imdb");
		$self->status("list file inconsistancies, they can usually be safely ignored");
	    }
	}
    }
    else {
	if ( $self->{errorCountInLog} == 0 ) {
	    $self->status("prep stage $stage failed (with no logged errors)");
	}
	else {
	    $self->status("prep stage $stage failed with $self->{errorCountInLog} errors in $self->{imdbDir}/stage$stage.log");
	}
    }
    return($ret);
}

1;