This file is indexed.

/usr/bin/tv_grab_na_dd is in xmltv-util 0.5.67-0.1.

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

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
#!/usr/bin/perl -w

eval 'exec /usr/bin/perl -w -S $0 ${1+"$@"}'
    if 0; # not running under some shell

=pod

=head1 NAME

tv_grab_na_dd - Grab TV listings for North America using Schedules Direct http://www.schedulesdirect.org

=head1 SYNOPSIS

    tv_grab_na_dd --help

    tv_grab_na_dd --version

    tv_grab_na_dd --capabilities

    tv_grab_na_dd --configure [--config-file FILE] [--dd-data FILE]
                              [--reprocess] [--auto-config add|ignore]
                              [--gui OPTION]

    tv_grab_na_dd --list-lineups [--config-file FILE] [--dd-data FILE]
                                 [--reprocess]

    tv_grab_na_dd [--config-file FILE] [--dd-data FILE]
                  [--reprocess] [--auto-config add|ignore]
                  [--days N] [--offset N] [--quiet] [--notrim]
                  [--old-chan-id] [--low-mem] [--output FILE]
                  [--list-channel] [--share SHAREDIR] [--list-times]
                  [--download-only] [--padd n] [--dropbadchar] [--agent NAME]

=head1 DESCRIPTION

This script downloads TV listings using Schedules Direct's data service,
converts it to XMLTV format, and outputs the results.

You must first register with Schedules Direct at: L<http://www.schedulesdirect.org> 

Schedules Direct is a non-profit organization whose mission is to provide
low-cost television program guide data to end-users of Open Source
and Freeware applications.

The raw data source is Tribune Media Service's Data Direct Service, which is
very similar to the free Zap2IT Labs service Tribune previously offerred.

While the service is not available for free, Schedules Direct strives
to keep costs as low as possible.

First you must become a member at the L<http://www.schedulesdirect.org>  site.

Next, you use that website to add lineup(s) to your account.

Next, you execute C<tv_grab_na_dd --configure> to set up the grabber.

Finally, you execute B<tv_grab_na_dd> with no arguments and it will output
listings in XML format to standard output.  See below for other options. 

Like many utilities, tv_grab_na_dd tries to exit with a "0" on success and something else 
on error.

=head1 Stand-alone options

=over

=item --help

Print a help message and exit.

=item --version

Show the version of the grabber.

=item --capabilities

Show which capabilities the grabber supports. For more
information, see L<http://wiki.xmltv.org/index.php/XmltvCapabilities>

=back

=head1 Mode selection (default is grab mode) 

=over

=item --configure

Activates configure mode.  If a config file already exists the values
are used as defaults.

=item --gui OPTION

Use this option to enable a graphical interface to be used.
OPTION may be 'Tk', or left blank for the best available choice.
Additional allowed values of OPTION are 'Term' for normal terminal output
(default) and 'TermNoProgressBar' to disable the use of Term::ProgressBar.

=item --list-lineups

Lists available lineups.  Only requires username in the config file. Used
by programs that automate the L</--configure> process.

=back

=head1 General Options

=over

=item --config-file
I<file>

Set the name of the configuration file, the default is B<~/.xmltv/tv_grab_na_dd.conf>.
This is the file created during L</--configure> mode.

=item --dd-data
I<file>

Store raw Data Direct data to this file. (default is a temporary file)

=item --reprocess

Don't get data from Data Direct, but reprocess a file saved with L<--dd-data|/"--dd-data I<file>">.

=item --auto-config I<add|ignore>

When used in --configure mode, updates the config file, removing old channels, and adding or
ignoring new channels.  Prompts are skipped if defaults are available in the current config file.

When used in grab mode, appends new channels to the config file.

=back

=head1 Grabber Mode options

=over

=item --days I<n>

Grab I<n> days.  The default is 7. 

=item --offset I<n>

Start N days after the default.

=item --quiet

Suppress some messages normally written to standard error.

=item --notrim

Data Direct includes shows in progress at the start time.  The default behavior
is to filter these shows out so data can be cleanly split between days.  This
option turns off that filter so you get shows in progress a tthe start time.

=item --old-chan-id

Use a channel id similar to the one used by the old B<tv_grab_na> grabber.

=item --low-mem

Omit all but the most basic program information. Reduces memory usage.

=item --output I<file>

Write xml to I<file> rather than standard output.

=item --list-channel

Same as B<--days> 0

=item --share I<SHAREDIR>

tv_grab_na_icons stores icons in I<SHAREDIR>/icons.  The share directory is set at install time,
but there may be times when it needs to be specified. (for example: no write access to the default share
directory)

=item --list-times

Report to STDERR the Schedules Direct blockedTime (not currently enforced)
and suggestedTime values to assist automated processes with scheduling.

=item --download-only

Don't generate any output, just fetch the data.  Personally I don't see the point,
but it was requested and easy to add.

=item --padd I<n>

Add <n> spaces to the front of the start date.  This is normally not needed,
but can be helpful in working around a Tribune problem when the request packet
spans TCP packets.  Recommended initial value is "20".  This is only needed if you get
"invalid start time" messages.  If this helps, please post results to the list.

=item --dropbadchar

DD data is supposed to be in UTF-8 format.  Sometimes DD sends bad characters
which cause a "Bad XML from DD" error.  This option causes those bad characters
to be deleted.

=item --agent NAME

appends NAME to the http agent string when fetching data.  This is a polite way to 
tell Schedules Direct which application is being used.  It helps developers know
how many people are using their application and gives applications credit towards 
free accounts.

=back

=head1 Automating configuration

Sometimes applications want to call B<tv_grab_na_dd> as a standalone application,
but automate the configure process.  The best way is to hook in to the XMLTV::Ask module,
but if that's not available, here is a solution.

=over

Step1. Application creates config file with username (and optionally password).

Step2. C<tv_grab_na_dd --dd-data lineups.xml --list-lineups> 

Step3. Application adds desired lineup to config file.

Step4. C<tv_grab_na_dd --dd-data lineups.xml --reprocess --auto-config add --list-channels>

Step5. Application edits config file as needed, and deletes lineups.xml.

=back

=head1 Grabber Timing

Data Direct offers a "suggested download time" that can be retrieved with the
"--list-times" option. Its use is encouraged.

=head1 Handling Multiple Linups

tv_grab_na_dd only outputs a single lineup. If your Schedules Direct
account has multiple lineups, they are all downloaded even though only one is output.

To process multiple lineups, use separate L<--config-file|/"--config-file I<file>">.
Separate config files are also handy if you need different channel sets for a lineup
(common with MythTV). To prevent re-downloading the data on subsequent passes, the
L</--reprocess> option is recommended.

Here's an example: (the = sign is optional, but helps readability)

 tv_grab_na_dd --config-file=lineup1.dat --output=lineup1.xml --dd-data=dd.xml
 tv_grab_na_dd --config-file=lineup2.dat --output=lineup2.xml --dd-data=dd.xml --reprocess
 tv_grab_na_dd --config-file=lineup3.dat --output=lineup3.xml --dd-data=dd.xml --reprocess

Each config file specifies the desired lineup and channel list.

If you want to merge the lineups into a single file, you can use tv_cat

 tv_cat lineup1.xml lineup2.xml lineup3.xml >guide.xml

=head1 Non-US/Canada listings. "fake" postal codes. 

TMS's Data direct service proivdes listings for a few non US/Canada locations.  These are
accessed with "fake" postal codes.  The following are available:

    147BERM Bermuda Cablevision
    366HAMI Hamilton, Bermuda Wow World on Wireless
    101VENE DirecTV Latin America
    904MEXI Mexico #1
    954MEXI Mexico #2
    512TRIN Trinidad Express
    782YOKO Yokota AFB, Japan. Americable International

For a more complete list, check the Schedules Direct FAQ

=head1 Adding icon links to listings

B<tv_grab_na_dd> checks for channel icons in a directory B<I<share>>/B<icons>.  The I<share> directory
is usually set during the install.  For windows exe users, it defaults to the location where
B<xmltv.exe> is.  B<tv_grab_na_icons> is available to download the icons.

=head1 Notes on channel lists

Channel lists can be configured both at the Schedules Direct website and through the grabber.  This is done to
allow multiple config files with different channel lists as Schedules Direct only supports a single channel map
per lineup.

Similarly, tv_grab_na_dd only supports a single channel mapping for a station. If multiple mappings 
are detected, only the first one is used and you are advised to adjust your Schedules Direct lineup.

=head1 Notes on episode numbers

Three episode-num formats are supplied (when available)

=over

=item xmltv_ns

always C<..a/b> for part C<a> of C<b>. First two xmltv_ns fields always blank.

=item dd_progid

TMS generated C<a.b.c/d> where C<a> is a unique program id, C<b> is a unique episode id,
C<c/d> is part C<c> of C<d> similar to xmltv_ns.

=item onscreen

Distributor-designated number corresponding to an episode of a specific show. Varies by distributor.

=back

=head1 Notes on passwords

If a password is stored in the config file, the config file should be properly protected.
Instead of storing the password in the config file, it can be omitted, and will be prompted for. 

=head1 Notes on lineup changes

Data Direct currently adds a channel to your lineup automatically when it is available.  When
B<tv_grab_na_dd> sees the new channel in the Schedules Direct lineup, it prints a message (and
potentially adds or ignores it based on --auto-config).

If you are sensitive to bandwidth issues, I would set B<--auto-config ignore> and periodically check
your B<--config-file> for ignored channels and remove from your Schedules Direct lineup.

=head1 Notes on previously-shown

Previous releases of tv_grab_na_dd set XMLTV's "date" field for DD "original-air-date" field.
The correct place for the data is "previously-shown->start"  The OAD is in both places temporarily
for compatibility reasons.

DD has dropped the "repeat" flag and replaced it with a "new" flag. Now we set "previously-shown

=head1 Known issues

none!

=head1 SEE ALSO

L<xmltv(5)>.

=head1 Author

Author/Maintainer: Robert Eden, rmeden@yahoo.com

=head2 Contributors:

=over

Ed Avis, ed@membled.com

Don Huettl, drh@huettl.net

Matti Airas, mairas@iki.fi (I used tv_grab_fi as a template)

and of course everyone else I forgot to mention. :)

=back

=cut

#################################################################
# initializations

use strict;
use XMLTV::Version '$Id: tv_grab_na_dd.in,v 1.91 2015/06/29 16:24:28 knowledgejunkie Exp $ ';
use XMLTV::Capabilities qw/baseline manualconfig share/;
use XMLTV::Description 'North America (Data Direct)';
use Data::Dumper;
use Date::Manip;
use Time::Local;
use SOAP::Lite;
use File::Temp qw(tempfile);
use Getopt::Long;
use XML::Twig 3.10;

use XMLTV;
use XMLTV::Ask;
use XMLTV::Config_file;
use XMLTV::ProgressBar;
use XMLTV::TZ qw(offset_to_gmt);
use XMLTV::Usage <<END
$0: get listings via Schedules Direct (http://schedulesdirect.org)
in XMLTV format

    tv_grab_na_dd --help

    tv_grab_na_dd --version

    tv_grab_na_dd --capabilities

    tv_grab_na_dd --configure [--config-file FILE] [--dd-data FILE]
                              [--reprocess] [--auto-config add|ignore]
                              [--gui OPTION]

    tv_grab_na_dd --list-lineups [--config-file FILE] [--dd-data FILE]
                                 [--reprocess]

    tv_grab_na_dd [--config-file FILE] [--dd-data FILE]
                  [--reprocess] [--auto-config add|ignore]
                  [--days N] [--offset N] [--quiet] [--notrim]
                  [--old-chan-id] [--low-mem] [--output FILE]
                  [--list-channel] [--share SHAREDIR] [--list-times]
                  [--download-only] [--padd n] [--dropbadchar] [--agent STRING]

END
;
#
# module version checking doesn't work with XMLTV version numbers
#
die "ERROR: XMLTV.PM 0.5.32 required\n" if $XMLTV::VERSION lt '0.5.32';

#
# Global Vars
# 
my $SHARE_DIR='/usr/share/xmltv'; # by grab/na_dd/tv_grab_na_dd.PL
my @messages;           # DD warnings.
my %chan_config;        # Active/inactive channels.
my %chan_id;            # quick channel id lookup
my %station;            # DD station data
my %lineups;            # DD channel mapping data
my %program;            # DD program data
my %crew;               # DD crew data
my %programGenre;       # DD Genre data
my @schedules;          # DD schedule list

my $bar;                # handle for status bar
my $count;              # record count (for status bar)
my $DEBUG          =0;  # debug mode
my $config_file;        # config file name
my $tz_offset=0;
my $start_time=time();
my $sched_count=0;        # record count;
my %old_lineups=();      # used for DD schema 1.2 -> 1.3 migration
my %icons=();            # holds icons (if present)

my $dd_user="";         # dd username
my $dd_pass="";         # dd password
my $dd_lineup="";       # dd lineup (empty all lineups)
my $dd_data;            # temp file handle to store DD data
my $dd_schema=undef;       # dd schema found
my $dd_data_name;       # filename for above
my $dd_data_size;       # amount of data returned 
my $dd_start;           # dd start time
my $dd_stop;            # dd stop time

my $opt_help;           # ask for help
my $opt_configure;      # configure mode
my $opt_config_file ;   # config_file_name
my $opt_gui ;           # use a gui for configuration
my $opt_output;         # output name
my $opt_days       =7;  # days to fetch
my $opt_offset     =0;  # day to start
my $opt_quiet      =0;  # supress messages
my $opt_lineup     =''; # limit results to one lineup
my $opt_old_chan_id=0;  # use tv_grab_na style chan ids
my $opt_low_mem    =0;  # use as little memory as you can
my $opt_dd_data    =''; # save dd data
my $opt_reprocess  =''; # reprocess dd data
my $opt_auto_config  =''; # auto add/ignore channels
my $opt_list_channels='';  
my $opt_list_lineups='' ;
my $opt_list_times=''   ;
my $opt_dropbadchar=0;  ;
my $opt_down_only=0     ;
my $opt_padd=0          ;
my $opt_tz_offset=undef;
my $opt_notrim=0;
my $opt_agent="";

#
# Process command line
#
foreach (@ARGV) {
    tr/_/-/ if /^--/; # older option style
}
GetOptions(
	       'help'          => \$opt_help,
    	   'configure'     => \$opt_configure,
    	   'config=s'      => \$opt_config_file,
    	   'config-file=s' => \$opt_config_file,
    	   'gui:s'         => \$opt_gui,
    	   'output=s'      => \$opt_output,
           'days=i'        => \$opt_days,
    	   'offset=i'      => \$opt_offset,
    	   'quiet'         => \$opt_quiet,
    	   'lineup=s'      => \$opt_lineup,
           'old_chan_id'   => \$opt_old_chan_id,
           'old-chan-id'   => \$opt_old_chan_id,
           'low_mem'       => \$opt_low_mem,
           'low-mem'       => \$opt_low_mem,
           'dd_data=s'     => \$opt_dd_data,
           'dd-data=s'     => \$opt_dd_data,
           'reprocess'     => \$opt_reprocess,
           'auto-config=s' => \$opt_auto_config,
           'auto_config=s' => \$opt_auto_config,
           'list-channels' => \$opt_list_channels,
           'list-lineups'  => \$opt_list_lineups,
           'list-times'    => \$opt_list_times,
           'download-only' => \$opt_down_only,
           'debug'         => \$DEBUG,
    	   'share=s'       => \$SHARE_DIR,
           'dropbadchars'  => \$opt_dropbadchar,
           'padd=i'        => \$opt_padd,
           'notrim'        => \$opt_notrim,
           'agent=s'       => \$opt_agent,
	  )
  or usage(0);
usage(1) if $opt_help;
die "ERROR: number of days must not be negative\n"         if ($opt_days < 0);
die "ERROR: must specify --dd_data during reprocess\n"     if $opt_reprocess and not $opt_dd_data;
die "ERRIR: --auto-config must be 'add' or 'ignore'\n"     if $opt_auto_config && $opt_auto_config !~ /^(add|ignore)$/;
die "ERROR: --down-only without --dd-data is pointless!\n" if $opt_down_only && ! $opt_dd_data;

$opt_days    = 0 if $opt_configure || $opt_list_channels || $opt_list_lineups;
XMLTV::Ask::init($opt_gui);
$config_file = XMLTV::Config_file::filename($opt_config_file, 'tv_grab_na_dd' , $opt_quiet);


########################################################################
#
# Load config file
#
if (-e $config_file && ( !$opt_configure || -s $config_file ))
{
    foreach (XMLTV::Config_file::read_lines($config_file))
    {
        next unless defined $_;
        chomp;
        my( $setting, $val ) = split( /:\s+/o, $_, 2 );

        if ( $setting =~ /^(not )?channel$/o )
        {
            $chan_config{$val} = $1 ? 0 : 1;
        }
        elsif ( $setting eq 'username' )
        {
            $dd_user = $val;
        }
        elsif ( $setting eq 'password' )
        {
            $dd_pass = $val;
#           print STDERR "\nWARNING: Password in config file, protect as required\n\n" unless $opt_quiet;
        }
        elsif ( $setting eq 'timezone' )
        {
            $opt_tz_offset  = $val;
            $opt_tz_offset='+0000'  if $opt_tz_offset =~ /UTC/i;
        }
        elsif ( $setting eq 'timeoffset' )
        {
            $opt_tz_offset  = $val;
            $opt_tz_offset='+0000'  if $opt_tz_offset =~ /UTC/i;
        }
        elsif ( $setting eq 'lineup' )
        {
            $dd_lineup = $val;
#
# special processing for dd_schema 1.2 -> 1.3
#
            if (exists $old_lineups{$dd_lineup})
            {
                print STDERR "WARNING: Lineup IDs have changed. Please run --configure\n";
                $dd_lineup = $old_lineups{$dd_lineup};
            }
        }
        elsif ( $setting eq 'auto-config' )
        {
            $opt_auto_config = $val;
        }
        else
        {
            warn "WARNING: Unknown setting: $setting, skipping.\n";
        }
    }
} # load config file

#
#
# start --configure mode
#

if ( $opt_configure )
{
    if ( ! $opt_auto_config )
    {
       while (1)
       {
         if (defined $ENV{TZ})
         {
             $opt_tz_offset=$ENV{TZ} unless defined $opt_tz_offset || $ENV{TZ} !~ /[+-]\d\d\d\d/;
         }
         $opt_tz_offset='+0000'  if (defined $opt_tz_offset && $opt_tz_offset =~ /UTC/i);
         $opt_tz_offset='+0000'  unless defined $opt_tz_offset;

         $opt_tz_offset=ask("

Time OFFSET Selection (note: not a timeZONE)
It is better to specify +0000 and let the final application
deal with a local conversion (helps with DST issues), but you
can specify a Time Offset if desired.
+0000 UTC
-0400 Eastern  Daylight
-0500 Eastern  Standard or Central Daylight
-0600 Central  Standard or Mountain Daylight
-0700 Mountain Standard or Pacific Daylight
-0800 Pacific  Standard
Timezone offset (+/-####) ($opt_tz_offset)") || $opt_tz_offset;
         last if $opt_tz_offset =~ /[+-]\d\d\d\d/;
       }

        say("
Schedules Direct registration required in advance. 
Sign up at http://www.schedulesdirect.org
(don't forget to add a lineup!)

    ");
        $dd_user=ask("Username ($dd_user):")|| $dd_user || die "ERROR: Schedules Direct Username Required\n";
        $dd_user=lc($dd_user); # force lower-case on username
        $dd_pass=ask_password("
WARNING: Storing the password in the config file is not secure
If password is blank, it will be prompted as needed(more secure)
Unsecured password ('x':delete,default:<keep>,):")|| $dd_pass;
    }
    $dd_pass='' if $dd_pass eq 'x';
} #configure mode

die "*ERROR* Username not specified. Please run --configure\n" unless $dd_user;
die "*ERROR* Lineup not specified.  Please run --configure\n"  unless $dd_lineup || $opt_list_lineups || $opt_configure;
die "*ERROR* Local timezone not yet supported. Please run --configure\n" unless defined $opt_tz_offset;
die "*ERROR* Bad timezone offset Please run --configure\n" unless $opt_tz_offset =~ /[+-]\d\d\d\d/;

$tz_offset = substr($opt_tz_offset,0,3)*3600+substr($opt_tz_offset,3,2)*60;
#$opt_tz_offset='UTC' unless $tz_offset;
print STDERR "Using TZ=<$opt_tz_offset> offset=<$tz_offset>\n" if $DEBUG;

#
# compute start/stop time
#
{
    if (int(Date::Manip::DateManipVersion) >= 6) {
        Date::Manip::Date_Init("SetDate=now," . offset_to_gmt($opt_tz_offset));
    } else {
        Date::Manip::Date_Init("TZ=" . offset_to_gmt($opt_tz_offset));
    }
#
# TMS bug causes errors around UTC midnight, so let's bump it by a second
#
    my $start = DateCalc("00:00:01","+ $opt_offset days") || die "ERROR: Can't compute <$opt_offset> days\n";
    my $stop  = DateCalc($start    ,"+ $opt_days   days") || die "ERROR: Can't compute <$opt_days> days\n";

#
# if days==0, back start time up by a minute to try and get only channels
#
    $start = DateCalc($start,"- 1 minute") if $opt_days==0;

    die "ERROR: start($start) before stop($stop)\n" unless $stop gt $start;
    
    $dd_start=UnixDate(Date_ConvTZ($start,offset_to_gmt($opt_tz_offset),"UTC"),"%Y-%m-%dT%H:%M:%SZ");
    $dd_stop =UnixDate(Date_ConvTZ($stop ,offset_to_gmt($opt_tz_offset),"UTC"),"%Y-%m-%dT%H:%M:%SZ");
    $dd_start=(' 'x$opt_padd).$dd_start if $opt_padd;

    print STDERR "dd_start: $start,$dd_start\n" if $DEBUG;
    print STDERR "dd_stop : $stop,$dd_stop\n" if $DEBUG;
} # compute date

#
# open dd data file (temp, or created)
#
if ($opt_reprocess)
{
    die "ERROR: $opt_dd_data file not found\n" unless -e $opt_dd_data;
    $dd_data_name = $opt_dd_data;
    $dd_data      = new IO::File("<$dd_data_name");
    $dd_data_size= -s $dd_data;

}
else
{
#
# get DD data
#
    #
    # open file to store DD XML
    #
    if ($opt_dd_data)
    {
        $dd_data_name = $opt_dd_data;
        $dd_data      = new IO::File("+>$dd_data_name");
    }
    else
    {
        ($dd_data,$dd_data_name) = tempfile('tv_grab_na_dd_XXXX',
                                             DIR    => File::Spec->tmpdir(),
                                             SUFFIX => '.tmp',
                                             UNLINK=>($DEBUG ? 0 : 1));
    }

    die "ERROR: Unable to open dd_data file <$dd_data_name>" unless defined $dd_data;
    
#
# Prompt for password (if needed)
#
    $dd_pass=~s/^\s//g;
    my $local_pass=$dd_pass;
    $local_pass=ask_password("Password for $dd_user: ")
      unless length $local_pass;

#
# Zap2IT's servers have a bug that causes errors when certain fields span IP packets.
# This is causing many users to report "BAD DATE" errors, and the Zap2IT servers guessing dates.
#
# Old versions of SOAP::Lite generated envelopes with 285 bytes of schema.
# Current SOAP::Lite generates 397 bytes!
# This hack seems to reduce the envelope to 276 bytes. Hopefully it will prevent the problem!
#
# Not sure if the Data Direct servers have the same problem, but why take a chance
#
    no warnings 'redefine';  # never warn on the SOAP redefine
    sub SOAP::Serializer::register_ns  { return 0; }

#
# Fetch data
# 
    sub SOAP::Transport::HTTP::Client::get_basic_credentials
    {
       return "$dd_user" => "$local_pass";
    }

    my $dd_service='http://dd.schedulesdirect.org/tech/tmsdatadirect/schedulesdirect/tvDataDelivery.wsdl';
	   $dd_service=$ENV{DD_SERVICE} if exists $ENV{DD_SERVICE};  # used for testing

    my $proxy='http://localhost/';
    if (exists $ENV{HTTP_PROXY})
    {
        $proxy=$ENV{HTTP_PROXY};
    }

    my $soap= SOAP::Lite
            -> service($dd_service)
            -> outputxml('true')
            -> proxy($proxy, options => {compress_threshold => 10000,
                                         timeout            => 420});

    $opt_agent='/'.$opt_agent if length($opt_agent)>1;
    $soap->transport->agent("xmltv/$XMLTV::VERSION".$opt_agent);

    if ($opt_list_times)
    {
        local $_=$soap->acknowledge;
        printf STDERR "%-15s|%s\n","blockedTime"  ,$1 if /<blockedTime>(.+)<.blockedTime>/m;
        printf STDERR "%-15s|%s\n","suggestedTime",$1 if /<suggestedTime>(.+)<.suggestedTime>/m;
    }

    print STDERR "Fetching from Schedules Direct " unless $opt_quiet;
    print STDERR "\n    dd_data is in $dd_data_name\n" if $DEBUG || $opt_dd_data;   

    my $time=time();
    my $raw_data=$soap->download($dd_start,$dd_stop);

#
# detect non-xml error messages
#
    die "Transport ERROR: $raw_data\n" if (! $soap->transport->is_success &&
                                           substr($raw_data,0,1) eq '>');
                                           
#
# Sometimes Zap2IT allows bad charcters 0x127-0x255 to sneak through.
# This causes TWIG to die... let's drop them if asked
#
    if ($opt_dropbadchar) {
        print STDERR "Filtering Bad Characters\n" unless $opt_quiet;
        $raw_data =~ s/[\x80-\xff]|se\&Ga|ay\&Les|\& //g;
    }

   if ($opt_down_only) {  # --download only exits before normal password check
       if ($raw_data =~ /HTTP Status 401/g)  {
           die "\n\nERROR: Login failure from Schedules Direct. Check user/password or try again later\n";
       }
   }

    $dd_data->print($raw_data);
    $dd_data->flush;
    $dd_data_size= -s $dd_data;
    undef $raw_data;

    die 'ERROR: got empty result from SOAP call' if $dd_data_size == 0;
    unless ($opt_quiet)
    {
        $time = int(time() - $time);
        printf STDERR "    Fetched %d k/bytes in %d seconds\n",$dd_data_size/1024,$time;
    }
} # get data

#
# quit if --download-only
#
exit(0) if $opt_down_only;

#
# load supporting details
#
my $found_fault=0;
my $twig=XML::Twig->new(   
         twig_roots    => { HTML => 1, message => 1, xtvd =>1, 'SOAP-ENV:Fault' => 1 },
		 twig_handlers => 
		      {
		         HTML     => sub {
                                  die "ERROR: FETCH ERROR".$_->first_child_text;
                		         },
                 xtvd  => sub {
                                  $dd_schema=$_->att('schemaVersion');
				  die "ERROR: did not see schemaVersion attribute in <xtvd>"
				    if not defined $dd_schema;
                                  $_->twig->purge;
                                  return 0;
                                 },
                   
                 message  => sub {
                                  push @messages, $_->first_child_text;
                                  $_->twig->purge;
                                  return 0;
                                 },

		         stations => sub { $_->twig->purge;  return 0;},
		         station  => sub {
                                  my $hash=$_->simplify;
                                  $station{$_->att('id')}=$hash;
                                  $_->twig->purge;
                                  return 0;
                		         },
		         lineups => sub { $_->twig->purge;  return 0;},
                 lineup  => sub {
                                  my $hash = $_->simplify;
                                  my $name = $_->att('userLineupName');
                                     $name = $_->att('name') unless defined $name;
                                  my $id   = $_->att('id');
#
# make sure map is a hash, even if only one station
#
                                  $hash->{map}=[$hash->{map}] if ref($hash->{map}) eq 'HASH';
#
# add sub-channels if needed
#
                                  foreach (@{$hash->{map}}) {
                                      $_->{channel}.="-".$_->{channelMinor} if exists $_->{channelMinor};
                                  }

                                  $hash->{orig_id}=$name;
                                  $hash->{name}   =$name;
                                  if (exists $lineups{$name})
                                  {
                                    $name.='-2'; # deal with dupe names
                                  }
#
# note. special processing for dd_schema 1.2 -> 1.3 conversion
#
                                  if ($id)
                                  {
                                    $old_lineups{$name}=$id;
                                    $lineups{$id}=$hash;
                                  }
                                  else
                                  {
                                    $lineups{$name}=$hash;
                                  }
                                  
                                  $_->twig->purge;
                                  return 0;
                                 },
		         programs=> sub { $_->twig->purge;  return 0;},
		         program => sub {
                                  my $hash=$_->simplify;

                                  if ($opt_low_mem)  # only store title/subtitle
                                  {
                                    $program{$_->att('id')}{title}=$hash->{title};
                                    $program{$_->att('id')}{'subtitle'}=$hash->{subtitle} if exists $hash->{subtitle};
                                    $program{$_->att('id')}{'originalAirDate'}=$hash->{originalAirDate} if exists $hash->{originalAirDate};
                                  }
                                  else
                                  {
                                    $program{$_->att('id')}=$hash;
                                  }
                                  $_->twig->purge;
                                  return 0;
                		         },  
                 productionCrew => sub { $_->twig->purge;  return 0;},
		         crew    => sub {
                                  unless ($opt_low_mem)
                                  {
                                    my $hash=$_->simplify;
                                    $crew{$_->att('program')}=$hash;
                                  }
                                  $_->twig->purge;
                                  return 0;
                  		          },
                 genres       => sub { $_->twig->purge;  return 0;},
		         programGenre => sub {
                                  unless ($opt_low_mem)
                                  {
                                    my $hash=$_->simplify;
                                    $programGenre{$_->att('program')}=$hash;
                                  }
                                  $_->twig->purge;
                                  return 0;
                  		          },
                schedule     => sub {
                                  my $twig=$_;
                                  push @schedules,$twig->simplify;
                                  $_->twig->purge;
                                  return 0;
                                  },
                 faultstring => sub {
                                  printf STDERR "\nFAULT: %s\n",$_->first_child_text;
                                  $_->twig->purge;
                                  $found_fault=1;
                                  return 1;
                                 },
		         _all_ => sub {  # for some reason this is not being processed last, can't do the purge
                                  unless ( $opt_quiet || $count++ % 1000 )
                                  {
                                     if ($bar) { $bar->update(tell($dd_data)) }
                                     else      { print STDERR "."            };
                                  }
                                  return 0;
                  		      },
               } # end of handlers
          );

unless ($opt_quiet)
{
    $bar = new XMLTV::ProgressBar('loading data',$dd_data_size+1);
}
seek($dd_data,0,0);  #rewind
eval { $twig->parse( $dd_data ) };

if ($@) {
#
# Sometimes when an error occurs TMS generates BAD XML.
# Before displaying a non-user-friendly message, let's see if TMS knows it has a problem
#
    my $xml="";
    seek($dd_data,0,0);  #rewind
    map {$xml .= $_} <$dd_data>;
    if ($xml =~ /HTTP Status 401/g)
    {
        die "\n\nERROR: Login failure from Schedules Direct. Check user/password or try again later\n";
    }

    if ($xml =~ /\<faultstring>(.+)\<.faultstring>/g)
    {
        my $faultstring  =$1;
        my ($faultnumber)= $xml =~ /\<faultnumber>(.+)\<\/faultnumber>/g;
        my  $faultcode  = join(" / ",$xml =~ /\<faultcode(.+)>(.+)\<\/faultcode>/g);
        die "\nERROR: Error Message received from Schedules Direct.
             message: $faultstring
             code   : $faultcode
             number : $faultnumber
  This is probably a known issue, please try again later.  If the problem
  persists, check the XMLTV-USERS list or the Schedules Direct forums for known issues
  and assistance.\n\n";
    } # faulstring
# let's not display this.. if the xml is big, can be trouble.
#   warn "\nWARNING: error parsing DD xml: $@\nPartial XML follows:\n$xml\n";
    warn "\nWARNING: error parsing DD xml: $@\n";
    my $first_line = 1;
    if ($@ =~ /at line (\d+)/) { $first_line = $1 }
    die "\nERROR: Bad XML from DD, cannot continue. Consider using --dropbadchar or Capture xml with --dd-data\n";
}


$bar->update($dd_data_size+1) if $bar;
$bar->finish() if $bar;

$twig=undef;  # destroy twig (just in case)

#
# print any messages
#
foreach (@messages)
{
   next if  $opt_quiet && /^Your subscription will expire/;
   print STDERR "NOTE: $_\n";
}

die "ERROR:
*** FAULT Message from Tribune detected.  See message above.
*** This is probably a known issue, please try again later.  If the problem
*** persists, check the XMLTV-USERS list or the Schedules Direct web page for
*** known issues and assistance.\n\n" if $found_fault;

die "ERROR: did not see <xtvd> element in downloaded content\n" if not defined $dd_schema;
warn "WARNING: DD Schema # is $dd_schema, check for upgrade\n" if $dd_schema > 1.3;

    

#
# --list-lineup mode
#
if ($opt_list_lineups)
{
    my $id_len=2;
    my $type_len=4;
    my $orig_len=6;
    my $dev_len=6;
    for my $id (sort keys %lineups)
    {
        my $len=length($id);
        $id_len=$len if $len>$id_len;

        $len=length($lineups{$id}{type}||'');
        $type_len=$len if $len>$type_len;

        $len=length($lineups{$id}{orig_id}||'');
        $orig_len=$len if $len>$orig_len;

        $len=length($lineups{$id}{device}||'');
        $dev_len=$len if $len>$dev_len;

    }


    printf STDOUT "%-${id_len}s|%-6s|%-${type_len}s|%-${orig_len}s|%-${dev_len}s|%s\n",
                                                    "Lineup ID",
                                                    "Postal",
                                                    "Type",
                                                    "OrigID",
                                                    "Device",
                                                    "Location";
    for my $id (sort keys %lineups)
    {
          printf STDOUT "%-${id_len}s|%-6s|%-${type_len}s|%-${orig_len}s|%-${dev_len}s|%s\n",$id,
                                                  ,$lineups{$id}{postalCode}||'',
                                                  ,$lineups{$id}{type}||'',
                                                  ,$lineups{$id}{orig_id}||'',
                                                  ,$lineups{$id}{device}||'',
                                                  ,$lineups{$id}{location}||'',
    }
    exit 0;    
}

#
# --configure stage2, process channel list
#
if ($opt_configure)
{
    my %chan_found=();
    $dd_lineup=$old_lineups{$dd_lineup} if exists $old_lineups{$dd_lineup};
    $dd_lineup=(sort keys %lineups)[0]  unless exists $lineups{$dd_lineup};
    if (! $opt_auto_config)
    {
        my @choices=map sprintf("%s|%s,%s",$_,
                                           $lineups{$_}{name},
                                           $lineups{$_}{type}),
                        sort keys %lineups;
        my $val=sprintf("%s|%s,%s",$dd_lineup,
                                   $lineups{$dd_lineup}{name},
                                   $lineups{$dd_lineup}{type});
                                           
        $val = ask_choice("\nWhich Lineup? ($dd_lineup)",$val,@choices);
        $dd_lineup = (split(/\|/,$val))[0];
    } # !opt_auto_config

        $opt_auto_config='add' if !$opt_auto_config && !ask_boolean("
The preferred method for controlling the channel lineup is through
the Schedules Direct web site, but you can omit channels here as well.
Do you want to skip some channels?",0);

    print "\n";

    # If the user expressed a default preference
    if ($opt_auto_config)
    {
        # Either add all the new channels
        if ($opt_auto_config eq 'add')
        {
            foreach (@{$lineups{$dd_lineup}{map}})
            {
                unless ($station{$_->{station}}{callSign})
                {
                    print STDERR "Warning $_->{channel} has no callsign. Skipping\n";
                    next;
                }
                my $key1=sprintf("%s %s",$_->{channel}, 
                                         $station{$_->{station}}{callSign});
                if (not defined $chan_config{$key1}) {
                    print STDERR "Adding new channel: $key1\n";
                    $chan_config{$key1}=1;
                }
            }
        }
        # or ignore them all
        else
        {
            foreach (@{$lineups{$dd_lineup}{map}})
            {  
                my $key2=sprintf("%s %s",$_->{channel}, 
                    $station{$_->{station}}{callSign});
                if (not defined $chan_config{$key2}) {
                    print STDERR "Ignoring new channel: (see docs about bandwidth issues) $key2\n";
                    $chan_config{$key2}=0;
                }
            }
        }
    } # auto config
    else  # There was no default for new channels, so we ask the user
    {
        # Construct the questions
        my @questions;
        foreach (@{$lineups{$dd_lineup}{map}})
        {  
            my $key3=sprintf("%s %s",$_->{channel}, 
                $station{$_->{station}}{callSign});
            
            push @questions, "Add channel $key3?";
        }
        # Ask the questions
        my @answers = ask_many_boolean( 1, @questions );
        # Save the answers
        my $i=0;
        foreach (@{$lineups{$dd_lineup}{map}})
        {  
            my $key4=sprintf("%s %s",$_->{channel}, 
                $station{$_->{station}}{callSign});
            
            $chan_config{$key4} = $answers[$i];
            $i++;
        }
        #
        # ask about auto-config for the config file
        #
            $opt_auto_config=0;
            if (ask_boolean("Lineups change periodically. The default for new stations is to notify you.\n".
                            "Do you want new stations to be automatically added?")) {
               $opt_auto_config="add";
            }
            elsif (ask_boolean("Do you want new stations to be ignored?")) {
               $opt_auto_config="ignore";
            }
        } # no --auto-config during configure

   
#
# Write the config file
#
    open(CONF,">$config_file") or die "ERROR: can't open config file: $config_file\n";
    print CONF "username: $dd_user\n";
    print CONF "password: $dd_pass\n" if $dd_pass;
    print CONF "timeoffset: $opt_tz_offset\n";
    print CONF "lineup:   $dd_lineup\n";
    print CONF "auto-config: $opt_auto_config\n" if $opt_auto_config;

    foreach (@{$lineups{$dd_lineup}{map}})
    {  
        my $key5=sprintf("%s %s",$_->{channel}, 
            $station{$_->{station}}{callSign});
        print CONF ( $chan_config{$key5} ? '' : 'not ' ), "channel: $key5\n";
        $chan_found{$key5} = 1;
    }
    
    foreach (sort keys %chan_config)
    {
        next if $chan_found{$_};
        print STDERR "Channel '$_' no longer exists\n";
    }
    close CONF;
    say( 'Configuration complete!' );
    exit 0;
} # --configure channel list

#
# Make sure we have a valid lineup
#
if ( exists $old_lineups{$dd_lineup} )
{
    print STDERR "WARNING: lineup ID has changed, please re-run configure\n";
    $dd_lineup=$old_lineups{$dd_lineup};
}

die "ERROR: Lineup ($dd_lineup} not found in data\n" unless exists $lineups{$dd_lineup};


#
# Look for icons
#
if (-d "$SHARE_DIR/icons")
{
   foreach (<$SHARE_DIR/icons/*>)
   {
        if (m!^.+/(.+?)\.!)
        {
            my $callsign=$1;
            my $uri=$_;

            next if /url$/i && exists $icons{$callsign};
            
            if (/url$/i)
            {
                open(FILE,$uri) || die "ERROR: opening icon file $uri\n";
                    $uri=<FILE>;
                    close FILE;
                chomp($uri);                
            }
            else
            {
#                $uri=~s!/!\\!g if $^O=~/win/i;
                $uri="file://".$uri;
            }
            $icons{$callsign}=[ {src => $uri } ],
        }
   }
}

#
# open output file
# 
my %w_args;
my $writer;
if (defined $opt_output) {
                            my $fh = new IO::File(">$opt_output");
                            die "ERROR: cannot write to $opt_output: $!" if not defined $fh;
                            $w_args{OUTPUT} = $fh;
                         }
$w_args{encoding} = 'ISO-8859-1';

$writer = new XMLTV::Writer(%w_args);
$writer->start( {
              'source-info-name'     => 'Schedules Direct',
              'source-info-url'      => 'http://www.schedulesdirect.org/',
              'generator-info-name'  => 'XMLTV/$Id: tv_grab_na_dd.in,v 1.91 2015/06/29 16:24:28 knowledgejunkie Exp $',
      	      'generator-info-url'   => 'http://www.xmltv.org/',
            });


#
# write stations, removing those we don't care about
#
my %seen_station;
my $got_multi_chan=0;
for my $map (@{$lineups{$dd_lineup}{map}})
{
    my $sid = $map->{station};
    my $station=$station{$sid};

    unless ($station->{callSign})
    {
       print STDERR "WARNING: Strange $map->{channel} has no callsign. Skipping\n";
       next;
    }

    if ($seen_station{$sid}++)
    {
    warn "WARNING: multiple channel mappings for '$station{$sid}{callSign}'\n";
    $got_multi_chan=1;
	next;
    }
    my $myid = sprintf("I%d.labs.zap2it.com",$sid);
    my $key=sprintf("%s %s",$map->{channel},$station->{callSign});

#
# detect new channel (appending to config file is lame, but it works)
#
    unless (exists $chan_config{$key})
    {
       $chan_config{$key}=0; # default ignore
       if ($opt_auto_config)
       {
          if ($opt_auto_config eq 'add') {
		$chan_config{$key}=1;
                print STDERR "Adding new channel: $key\n" unless $opt_quiet;
           }

          open(CONF,">>$config_file") or die "ERROR: can't open config file for update: $config_file\n";
          print CONF ( $chan_config{$key} ? '' : 'not ' ), "channel: $key\n";
          close CONF;
       }
       else
       {
           print STDERR "WARNING: New channel, rerun --configure and/or change your Schedules Direct config: $key\n";
       }
    } # new channel

    next unless $chan_config{$key}; #skip?

#
# generate tv_grab_na channel number
#
    if ($opt_old_chan_id)
    {
       $myid = sprintf("C%s%s.zap2it.com",$map->{channel},lc($station->{callSign}));
    }

#
# Set display names:
#           channel + callSign
#           channel + callSign + lineup
#           channel (only)
    my @names;
    push @names, [ sprintf("%s %s"   ,$map->{channel},$station->{callSign})];
    push @names, [ sprintf("%s %s %s",$map->{channel},$station->{callSign},$dd_lineup)];
    push @names, [ $map->{channel} ];

# 
# Now add display names for the fcc
#
    push @names,[sprintf("%d %s %s",$station->{fccChannelNumber},
                                    $station->{callSign},
                                    'fcc')] if exists $station->{fccChannelNumber};

#
# round up the rest we have
#
    for my $key (qw(callSign name affiliate))
    {
            push @names,[ $station->{$key} ] if exists $station->{$key};
    }
    
    unless (@names)
    {
        warn "WARNING: No display names defined for channel $myid\n";
        next;
    }

    $writer->write_channel({ 'id'           => $myid,
                             'display-name' => \@names,
                             'icon'         => $icons{$station->{callSign}},
                             });

    $chan_id{$sid}=$myid;
} # output  channels
warn "WARNING: Multiple channel mappings found, please adjust Schedules Direct lineup\n" if $got_multi_chan;

#
# list channels only
#
if ($opt_list_channels)
{
   $writer->end();
   exit 0;
}

#
# prepare to output schedule
#
unless ($opt_quiet)
{
    $bar = new XMLTV::ProgressBar('Writing schedule',$#schedules+2);
}

foreach $_ (@schedules) {
     $sched_count++;
     unless ( $opt_quiet || $sched_count % 10 )
     {
       if ($bar) { $bar->update($sched_count) }
       else      { print STDERR "."           };
    }

   my %prog=();
   my $ptr;

# Skip programs not in our lineup and shows that start before our start time
# (dd provides shows in progress and it messes up splitting/merging)
  next unless exists $chan_id{$_->{station}};
  next unless ($opt_notrim || $_->{time} ge $dd_start);
        
#
# we generated a TZ offset a while back... this is twice as fast as Date::Manip!
#
                    my $start = timegm(
                                        int( substr($_->{time},17,2) ),
                                        int( substr($_->{time},14,2) ),
                                        int( substr($_->{time},11,2) ),
                                        int( substr($_->{time},8,2) ),
                                        int( substr($_->{time},5,2) - 1 ),
                                        int( substr($_->{time},0,4) - 1900 ) );
                     my @gStart = gmtime( $start+$tz_offset );
                     $prog{start} = sprintf("%d%02d%02d%02d%02d%02d %s",
		                             $gStart[5] + 1900,
					     $gStart[4] + 1,
					     @gStart[3,2,1,0],
					     $opt_tz_offset);

                     my $h = substr($_->{duration},2,2);
                     my $m = substr($_->{duration},5,2);
                     my $stop = $start + ( ( $h * 60 ) + $m ) * 60;
                     my @gStop = gmtime( $stop+$tz_offset );
                     $prog{stop} = sprintf("%d%02d%02d%02d%02d%02d %s",
		                            $gStop[5] + 1900,
            					    $gStop[4] + 1,
			            		    @gStop[3,2,1,0],
					                $opt_tz_offset);

                     $prog{channel} = $chan_id{$_->{station}};
                     $prog{audio}{stereo}='stereo'          if exists $_->{stereo};
                     $prog{audio}{stereo}=lc($_->{dolby})   if exists $_->{dolby};
                     $prog{'previously-shown'}={}           if ! exists $_->{new}
                                                               && $_->{program} =~ /^EP|^SH/;

                     push @{$prog{subtitles}},{type=>'teletext'}  if exists $_->{closeCaptioned};
                     push @{$prog{subtitles}},{type=>'onscreen'}  if exists $_->{subtitled};

                     if (exists $_->{hdtv})
                     {
                         $prog{video}{aspect}="16:9";
                         $prog{video}{quality}="HDTV";
                     }
                     
                     if (exists $_->{tvRating})
                     {
                        $_->{tvRating} =~ s/^TV/TV-/  unless $_->{tvRating} =~ /-/;
                        push @{ $prog{rating} }, [$_->{tvRating},'VCHIP'];
                     }

#
# Note, provide multi-part info in xmltv_ns format for those apps that need it 
#
                     if (exists $_->{part}{number} && exists $_->{part}{total})
                     {
                         push @{$prog{'episode-num'}}, [sprintf("..%d/%d",
                                                           $_->{part}{number}-1,
                                                           $_->{part}{total}),
                                                        'xmltv_ns'];
                     }
                                                       
#
# Store TMS Show ID, Episode ID, part in <episode-num> of "id.episode.part/total"
# using our own numbering system.
#
                     if ( $_->{program} =~ /^(..\d{8})(\d{4})$/ )
                     {
                       my $value =sprintf("%s.%s",$1,$2);
                          $value.=sprintf(".%d/%d",$_->{part}{number}-1,
                                                   $_->{part}{total}) if exists $_->{part}{number} && exists $_->{part}{total};
                       push @{$prog{'episode-num'}}, [$value,'dd_progid'];
                     }


#
# add elements from program Genre tag
# Note: before program so Genra comes before ShowType in <category>
#
                     if ($ptr = $programGenre{$_->{program}})
                     {
                         if (ref $ptr->{genre} eq 'HASH')
                        {
                            push @{$prog{category}},[$ptr->{genre}{class},'en']
                        }
                        else
                        {
                            foreach (@{$ptr->{genre}})
                            {
                                push @{$prog{category}},[$_->{class},'en'];
                            }
                        }
                     } # Genra items

#
# add elements from program tag
#
#
                     if (! ($ptr = $program{$_->{program}}) ) {
                        warn "\nBad DD data: No program tag for $_->{program}\n";
                        next;
                     } else {
                        $prog{title}        =[[$ptr->{title},      'en']] if exists $ptr->{title};
                        $prog{'sub-title'}  =[[$ptr->{subtitle}   ,'en']] if exists $ptr->{subtitle};
                        $prog{desc}         =[[$ptr->{description},'en']] if exists $ptr->{description};
#
# Note: originalAirDate belongs in the "previosly-shown" tag.
# It was put in {date} in error.  Let's keep it in {date} for compatibility
# reasons.  If we have a copyright date, we change it anyway
#
# Note, {original-air-date} has a different meaning for SH episodes
#
                     if ( exists $ptr->{originalAirDate} && $_->{program} !~ /^SH/) 
                     {
                        $prog{'previously-shown'}{start}=$ptr->{originalAirDate}.'000000';

                        $prog{'previously-shown'}{start}=~ s/-//g;
                     }

                        $prog{date}         =$ptr->{originalAirDate}      if exists $ptr->{originalAirDate}
                                                                             && $_->{program} =~ /^EP/;
                        $prog{date}         =$ptr->{year}                 if exists $ptr->{year};
                        $prog{date}         =~ s/-//g                     if exists $prog{date};


                        if (exists $ptr->{runTime})
                        {
                            if ($ptr->{runTime} !~ /PT\d\dH\d\dM/)
                            {
                                printf STDERR "WARNING: bad runTime <%s> detected for %s\n",
                                               $ptr->{runTime},$_->{program} unless $opt_quiet;
                            }
                            else
                            {
                                $prog{length}       = substr($ptr->{runTime},2,2)*3600+
                                                  substr($ptr->{runTime},5,2)*60;
                            }
                        }

                        if (exists $ptr->{advisories})
                        {
                           if (ref $ptr->{advisories}{advisory})
                           {
                              for my $val (@{$ptr->{advisories}{advisory}})
                              {
                                push @{$prog{rating}},[$val,'advisory'];
                              }
                           }
                           else
                           {
                              push @{$prog{rating}},[$ptr->{advisories}{advisory},'advisory'];
                           }
                        }
                        
                        if (exists $ptr->{mpaaRating})
                        {
                            if ($ptr->{mpaaRating} =~ /\*/)
                            {
                                printf STDERR "WARNING: bad mpaaRating <%s> detected for %s.\n",
                                               $ptr->{mpaaRating},$_->{program} unless $opt_quiet;
                            }
                            else
                            {
                                push @{ $prog{rating}  }, [$ptr->{mpaaRating},'MPAA'];
                            }
                        }
                       
                        if (exists $ptr->{colorCode})
                        {
                            $prog{video}{colour}=1; # too bad this just wants a boolean... 
                            $prog{video}{colour}=0 if $ptr->{colorCode} =~ /^B/i;
                        }

                        if (exists $ptr->{starRating})
                        {
                            if ($ptr->{starRating} =~ /\a/)
                            {
                                printf STDERR "WARNING: bad starRating detected for %s.\n",
                                               $ptr->{starRating},$_->{program} unless $opt_quiet;
                            }
                            else
                            {
                                 my $star=length($ptr->{starRating});
                                 if ($ptr->{starRating} =~ /\+$/)
                                 {
                                      $star -= .5;
                                      $prog{'star-rating'}=[sprintf("%1.1f/%d",$star,4)];
                                 }
                                 else
                                 {                              
                                      $prog{'star-rating'}=[sprintf("%d/%d",$star,4)];
                                 }
                            }
                        } # star rating

#
# if a show is new, let's make sure we know it (yes, we lose originalAirDate)
#
                     delete $prog{'previously-shown'}  if exists $_->{new};



                     push @{$prog{category}}, ['Movie','en' ]             if $_->{program}=~ /^MV/;
                     push @{$prog{category}}, ['Sports','en' ]            if $_->{program}=~ /^SP/;
                     push @{$prog{category}}, [$ptr->{showType}   ,'en' ] if exists $ptr->{showType};

                     push @{$prog{'episode-num'}}, [$ptr->{syndicatedEpisodeNumber},'onscreen']  if exists $ptr->{syndicatedEpisodeNumber};
                     } # %program items


#
# add elements from crew tag
#
                     if ($ptr = $crew{$_->{program}})
                     {
                        my ( @director, @actor, @writer, @adapter, @producer,
                             @presenter, @commentator, @guest );
                        $ptr->{member}=[$ptr->{member}] if (ref $ptr->{member} eq 'HASH');
                        foreach (@{$ptr->{member}})
                        {
			    next unless exists $_->{role};
                            my $name="";
                            $name.=$_->{givenname}." " unless ref $_->{givenname};
                            $name.=$_->{surname}       unless ref $_->{surname};
                            push @actor     ,$name if $_->{role} eq 'Actor';
                            push @guest     ,$name if $_->{role} eq 'Guest Star';
                            push @presenter ,$name if $_->{role} eq 'Host';
                            push @director  ,$name if $_->{role} eq 'Director';
                            push @producer  ,$name if $_->{role} eq 'Executive Producter';
                            push @producer  ,$name if $_->{role} eq 'Producer';
                            push @writer    ,$name if $_->{role} eq 'Writer';
                        }

                        $prog{credits}{actor    }=\@actor     if @actor   ;
                        $prog{credits}{director }=\@director  if @director;
                        $prog{credits}{guest    }=\@guest     if @guest;
                        $prog{credits}{presenter}=\@presenter if @presenter;
                        $prog{credits}{producer }=\@producer  if @producer;
                        $prog{credits}{writer   }=\@writer    if @writer;
                     } #crew items

#
# write record
#
                     $writer->write_programme(\%prog);
}; # schedule loop

    $bar->update($#schedules+1) if $bar;
    $bar->finish() if $bar;

    $writer->end();

    printf STDERR "\nDownloaded %d programs in %d seconds\n",$sched_count,time()-$start_time
        unless $opt_quiet;


exit(0);