#!/usr/bin/perl -w

=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 Schedules Direct's SD-DD service, which purchases
Data from Gracenote (formerly known as Tribune Media Services).

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 SD-DD 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 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

Gracenote 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;
use XMLTV::Version "$XMLTV::VERSION";
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::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 ='c:/share/xmltv';
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='https://dd.schedulesdirect.org/tech/tmsdatadirect/schedulesdirect/ssl_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("tv_grab_na_dd/$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 ",($ENV{DD_SERVICE}?$dd_service:"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 "\nBad username/password\n"     if $soap->transport->code  == 401;
	die "\nAccount Expired.Bad username/password\n"     if $soap->transport->code  == 402;
	die Error $soap->transport->code." ".$soap->transport->status."\n" unless $soap->transport->is_success == 1;
#    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 SD-DD generates BAD XML.
# Before displaying a non-user-friendly message, let's see if SD-DD 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 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};
	die "No lineups on the server. Please assign one from the web page\n" unless scalar %lineups;
    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 SD-DD',
              'source-info-url'      => 'http://www.schedulesdirect.org/',
              'generator-info-name'  => "XMLTV/$XMLTV::VERSION/tv_grab_na_dd",
      	      'generator-info-url'   => 'https://github.com/xmltv/xmltv',
            });


#
# 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 Gracenote 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 @guest     ,$name if $_->{role} eq 'Guest';
                            push @presenter ,$name if $_->{role} eq 'Host';
                            push @director  ,$name if $_->{role} eq 'Director';
                            push @producer  ,$name if $_->{role} eq 'Executive Producer';
                            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);

