#!/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_nl - Grab TV listings for Holland.

=head1 SYNOPSIS

tv_grab_nl --help

tv_grab_nl [--config-file FILE] --configure

tv_grab_nl [--config-file FILE] [--output FILE] [--days N]
           [--offset N] [--quiet] [--fast]

=head1 DESCRIPTION

Output TV listings for several channels available in Holland.
The data comes from www.tvgids.nl. The grabber relies on
parsing HTML so it might stop working at any time.

First run B<tv_grab_nl --configure> to choose, which channels you want
to download. Then running B<tv_grab_nl> with no arguments will output
listings in XML format to standard output.

B<--configure> Prompt for which channels,
and write the configuration file.

B<--config-file FILE> Set the name of the configuration file, the
default is B<~/.xmltv/tv_grab_nl.conf>.  This is the file written by
B<--configure> and read when grabbing.

B<--output FILE> Write to FILE rather than standard output.

B<--days N> Grab N days.  The default is one week.

B<--offset N> Start N days in the future.  The default is to start
from today.

B<--fast> Only fetch summary information for each programme. This is
only title, start/stop times, categories.

B<--quiet> Suppress the progress messages normally written to standard
error.

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

B<--version> Show the version of the grabber.

B<--help> Print a help message and exit.

=head1 SEE ALSO

L<xmltv(5)>.

=head1 AUTHOR

latest patch submitted by Teus Hagen
maintainer was Eric Bus (xmltv@fambus.nl).

First version by Guido Diepen and Ed Avis (ed@membled.com).
Originally based on tv_grab_fi by Matti Airas.

=cut

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

use strict;
use XMLTV::Version '$Id: tv_grab_nl,v 1.83 2015/06/28 08:33:44 knowledgejunkie Exp $ ';
use XMLTV::Capabilities qw/baseline manualconfig cache share/;
use XMLTV::Description 'Holland';
use Getopt::Long;
use Data::Dumper;
use HTML::TreeBuilder;
use HTML::Entities; # parse entities
use HTTP::Cache::Transparent;
use IO::File;
#use URI;
#use Date::Manip;
use Date::Parse;
use Date::Format;
use DateTime;
use Encode;
use XMLTV;
use XMLTV::Memoize;
use XMLTV::ProgressBar;
use XMLTV::Ask;
use XMLTV::Config_file;
use XMLTV::DST;
use XMLTV::Get_nice;
use XMLTV::Mode;
use XMLTV::Date;
# Todo: perhaps we should internationalize messages and docs?
use XMLTV::Usage <<END
$0: get Dutch television listings in XMLTV format
To configure: $0 --configure [--config-file FILE]
To grab listings: $0 [--config-file FILE] [--output FILE] [--days N]
        [--offset N] [--quiet] [--fast]
To show capabilities: $0 --capabilities
To show version: $0 --version
END
  ;

# Use Log::TraceMessages if installed.
BEGIN {
    eval { require Log::TraceMessages };
    if ($@) {
	*t = sub {};
	*d = sub { '' };
    }
    else {
	*t = \&Log::TraceMessages::t;
	*d = \&Log::TraceMessages::d;
	Log::TraceMessages::check_argv();
    }
}

# Function prototypes.
sub time_to_str( $ );
sub get_channels();
sub get_programmes( $$$ );
sub parse_dutch_date( $ );
sub process_details_page( $ );

# Whether zero-length programmes should be included in the output.
my $WRITE_ZERO_LENGTH = 0;

# Base timezone for the Netherlands.  Summer time is one hour ahead of
# this.
#
my $TZ = '+0100';

# default language
my $LANG = 'nl';

# character encoding of output file
my $ENCODING = 'ISO-8859-1';

######################################################################
# get options

# Get options, including undocumented --cache option.
XMLTV::Memoize::check_argv('XMLTV::Get_nice::get_nice_aux');
my ($opt_days, $opt_offset, $opt_help, $opt_output,
    $opt_configure, $opt_config_file, $opt_gui, $opt_quiet,
    $opt_list_channels, $opt_fast, $opt_share, $opt_debug);
$opt_days   = 7; # default
$opt_offset = 0; # default
$opt_debug  = 0;
GetOptions('days=i'        => \$opt_days,
	   'offset=i'      => \$opt_offset,
	   'help'          => \$opt_help,
	   'configure'     => \$opt_configure,
	   'config-file=s' => \$opt_config_file,
           'gui:s'         => \$opt_gui,
	   'output=s'      => \$opt_output,
	   'quiet'         => \$opt_quiet,
	   'fast'	   => \$opt_fast,
	   'list-channels' => \$opt_list_channels,
	   'share=s'       => \$opt_share,         # undocumented
	   'debug'         => \$opt_debug,         # undocumented
	  )
  or usage(0);

my $opt_slow = !$opt_fast;  # configure the old version's 'slow' flag (this is now the default unles --fast is specified)

if( defined $opt_offset && ( $opt_offset < 0 || $opt_offset > 6 ) ) {
	print '!! Offset must be between 0-6 (0 is today), using default (0)',"\n";
	$opt_offset = 0;
}

if( defined $opt_days && ( $opt_days < 1 || $opt_days + $opt_offset > 7 ) ) {
	print '!! Days must be between 1-7, using default (7)',"\n";
	$opt_days = 7 - $opt_offset;
}

usage(1) if $opt_help;

# Initialise the web page cache
HTTP::Cache::Transparent::init( { 
    BasePath => get_default_cachedir(),
    NoUpdate => 4*3600,         # cache time in seconds
    MaxAge => 24,               # flush time in hours
    Verbose => $opt_debug,
} );

XMLTV::Ask::init($opt_gui);

my $mode = XMLTV::Mode::mode('grab', # default
			     $opt_configure => 'configure',
			     $opt_list_channels => 'list-channels',
			    );

# File that stores which channels to download.
my $config_file
  = XMLTV::Config_file::filename($opt_config_file, 'tv_grab_nl', $opt_quiet);

if ($mode eq 'configure') {
    XMLTV::Config_file::check_no_overwrite($config_file);
    open(CONF, ">$config_file") or die "cannot write to $config_file: $!";

    # Get channels, and download what we can from the site.  When
    # configuring it's useful to download at least something as a
    # check that the site is reachable etc.
    #
    my $bar = new XMLTV::ProgressBar('getting list of channels', 1)
      if not $opt_quiet;
    my %channels = get_channels();
    die 'no channels could be found' if (scalar(keys(%channels)) == 0);
    update $bar if not $opt_quiet;
    $bar->finish() if not $opt_quiet;
    
    # Ask about each channel.
    my @chs = sort { $a <=> $b } keys %channels;
    my @names = map { $channels{$_}->{'name'} } @chs;
    my @qs = map { "add channel $_?" } @names;
    my @want = ask_many_boolean(1, @qs);

    print CONF "# Channel ID\t\t\t\t  Channel name\n";

    foreach (@chs) {
    	my $w = shift @want;
        my $name = shift @names;
        
    	warn("cannot read input, stopping channel questions"), last
    	  if not defined $w;
    	# No need to print to user - XMLTV::Ask is verbose enough.

    	# Print a config line, but comment it out if channel not wanted.
    	print CONF '# ' if not $w;
        print CONF "channel $_";
        print CONF "\t\t\t\t# $name\n";
    }

    close CONF or warn "cannot close $config_file: $!";
    say("Finished configuration.");

    exit();
}

# Not configuring, we will need to write some output.
die if $mode ne 'grab' and $mode ne 'list-channels';

# But if grabbing, check the config file is sane before we write
# anything.
#
my @config_lines;
if ($mode eq 'grab') {
    @config_lines = XMLTV::Config_file::read_lines($config_file);
}

my %w_args;
if (defined $opt_output) {
    my $fh = new IO::File(">$opt_output");
    die "cannot write to $opt_output: $!" if not defined $fh;
    $w_args{OUTPUT} = $fh;
}
$w_args{encoding} = $ENCODING;
my $writer = new XMLTV::Writer(%w_args);
# TODO: standardize these things between grabbers.
$writer->start
  ({ 'source-info-url'     => 'http://www.tvgids.nl/',
     'source-data-url'     => 'http://www.tvgids.nl/',
     'generator-info-name' => 'XMLTV',
     'generator-info-url'  => 'http://www.xmltv.org/'
   });

if ($mode eq 'list-channels') {
    my $bar = new XMLTV::ProgressBar('getting list of channels', 1)
      if not $opt_quiet;

    # Don't do any page fetches - assume the contents of the channels
    # file has already been checked enough.
    #
    my %channels = get_channels();
    die 'no channels could be found' if (scalar(keys(%channels)) == 0);
    update $bar if not $opt_quiet;

    foreach my $ch_did (sort(keys %channels)) {
    	my $ch_name = $channels{$ch_did}->{'name'};
    	my $ch_xid = "$ch_did.tvgids.nl";
    	$writer->write_channel({ id => $ch_xid,
    	   'display-name' => [ [ $ch_name ] ],
           'icon' => [{'src' => $channels{$ch_did}->{'url'}}] });
    }

    $writer->end();
    $bar->finish() if not $opt_quiet;
    exit();
}

# Not configuring or writing channels, must be grabbing listings.
die if $mode ne 'grab';
my %channels = get_channels();
my (@channels, $ch_did, $ch_name);
my $line_num = 0;
my $warned_old_format = 0;
my $bad = 0;

foreach (@config_lines) {
    ++ $line_num;
    next if not defined;

    if (/^channel:?\s+(\S+)\s+(.+)/) {
    	# Old format storing display-names in the config file.  Well,
    	# if they're there we ought to check them.
    	#
    	$ch_did = $1;
    	$ch_name = $2;
    	$ch_name =~ s/\s*$//;
    	push @channels, $ch_did;
    	$channels{$ch_did} = $ch_name;
    	warn "$config_file format needs upgrading, rerun --configure\n"
    	  unless $warned_old_format++;
    }
    elsif (/^channel\s+(\S+)\s*$/) {
       	push @channels, $1;
    }
    else {
       	warn "$config_file:$line_num: bad line\n";
      	$bad = 1;
    }
}
die "$config_file has errors, not continuing\n" if $bad;

######################################################################
# begin main program

# $opt_offset is taken into account later, we don't need to lie about
# $now.  This does make it impossible to use --offset together with
# --cache to reuse an old cache file from a few days ago - to do that
# you need to change $now below.  But --cache is undocumented so I
# don't consider this a problem.
#
my $now = parse_date('now');
# Any Date_Init('TZ=UTC') would go here.  But it may not be needed
# with parse_local_date().
#

my @to_get;

# We now fetch a complete page per channel
# This page contains all the program links for the specified days
for( my $i = $opt_offset; $i < ($opt_days+$opt_offset); $i++ )
{
    foreach $ch_did (@channels) {
        my $ch_xid = "$ch_did.tvgids.nl";
   	    #my $url = 'http://www.tvgids.nl/zoeken/'."?q=&d=$i&z=$ch_did&t=0&g=&v=0";
        my $url = "http://www.tvgids.nl/json/lists/programs.php?channels=$ch_did&day=$i";

   	    push @to_get, [ $url, $ch_xid, $ch_did, $i ];
    }
}

# programme store - stores programmes within starttime within channel (so we can check for duplicates)
#      @{ $programmes->{ $ch_id }->{ $p->{'start_epoch'} } 
my $programmes = {};

my $bar = new XMLTV::ProgressBar('Downloading schedules...', scalar @to_get)
  if not $opt_quiet;

# time limits for grab
my $grab_start = DateTime->today(time_zone => 'Europe/Amsterdam')->epoch() + ($opt_offset * 86400);
my $grab_end = $grab_start + ($opt_days * 86400);
#print STDERR "\n start/end grab: $grab_start $grab_end \n";

foreach (@to_get) {
    my ($url, $ch_xmltv_id, $ch_tvgids_id, $i) = @$_;
    die if ref $url;

    #my $start_day = UnixDate(DateCalc($now, "+ $i days"), '%Y-%m-%d');
		
    get_programmes ($url, $ch_xmltv_id, $ch_tvgids_id);    

 	  update $bar if not $opt_quiet;
}
$bar->finish() if not $opt_quiet;


# All data has been gathered. Restructure the data for XMLTV writer.
            			#
my @to_write = ();
foreach ( keys %{$programmes} ) {
    my $_ch_progs = $programmes->{$_};
    foreach ( sort keys %{$_ch_progs} ) {
        my $_dt_progs = $_ch_progs->{$_};
        foreach (@{ $_dt_progs }) {
            push @{to_write}, $_;
            			}
            			}
    }

# write the channels info
foreach $ch_did (@channels) {
    my $ch_name = $channels{$ch_did}->{'name'};
    my $ch_xid = "$ch_did.tvgids.nl";
    $writer->write_channel({ id => $ch_xid,
    	   'display-name' => [ [ $ch_name ] ],
           'icon' => [{'src' => $channels{$ch_did}->{'url'}}] });
	}

# write the programmes info
$writer->write_programme($_) foreach @to_write;

	#
$writer->end();

######################################################################
# subroutine definitions

#my $warned_bad_chars;
#sub tidypage( $ ) {
#    for (my $tmp = shift) {
#    	tr/\221\222/''/;
#    	if (tr/\012\015\040-\176\240-\377//dc) {
#    	    warn 'removing bad characters' unless $warned_bad_chars++;
#    	}
#    	return $_;
#    }
#}

# Remove bad chars from entire page
sub tidypage( $ ) {
    my $html = shift;
    $html =~ s/(\s)&nbsp;/$1/og;    # replace 'space-&nbsp;' with 'space'
    $html =~ s/&nbsp;/ /og;         # replace any remaining &nbsp; with space
    $html =~ s/&shy;//og;           # delete soft hyphens
    return $html;
}

# Remove bad chars from an element
sub tidy( $ ) {
    my $html = shift;
    return $html if !defined $html;	
    $html =~ s/(\s)\xA0/$1/og;    # replace 'space-&nbsp;' with 'space'
    $html =~ s/\xA0/ /og;         # replace any remaining &nbsp; with space
    $html =~ s/\xAD//og;           # delete soft hyphens
    return $html;
}

sub trim( $ ) {
    # Remove leading & trailing spaces
    $_[0] =~ s/^\s+|\s+$//g;
    return $_[0];
}
    
sub dedupe( @ ) {
    # Remove duplicates from an array
    my %temp_hash = map { $_, 0 } @_;
    return keys %temp_hash;
}

sub dedupepreserve( @ ) {
    # Remove duplicates from an array preserving the original sequence
    my (@unique, %seen) = ((),());
    foreach ( @_ ) {
      next if $seen{ lc( $_ ) }++;
      push @unique, $_;
    	        }
    return @unique;
}

sub time_to_str( $ ) {
    my $input = shift;

    # Replace months
	$input =~ s/\bjanuari\b/1/i;
	$input =~ s/\bfebruari\b/2/i;
	$input =~ s/\bmaart\b/3/i;
	$input =~ s/\bapril\b/4/i;
	$input =~ s/\bmei\b/5/i;
	$input =~ s/\bjuni\b/6/i;
	$input =~ s/\bjuli\b/7/i;
	$input =~ s/\baugustus\b/8/i;
	$input =~ s/\bseptember\b/9/i;
	$input =~ s/\boktober\b/10/i;
	$input =~ s/\bnovember\b/11/i;
	$input =~ s/\bdecember\b/12/i;
	$input =~ s/, / /i;
    
    if( $input =~ /(\d\d?) (\d{1,2}) (\d{4}) (\d\d:\d\d) *- *(\d\d:\d\d) uur/ ) {
    	return ( "$3-$2-$1 $4:00", "$3-$2-$1 $5:00" );
    }
    elsif( $input =~ /(\d\d?) (\d{1,2}) (\d{4}) - *(\d\d):(\d\d) uur/ ) {
    	return ( "$4-$3-$2 $4:".($5-30).":00", "$3-$2-$1 $4:$5:00" );
    }
    elsif( $input =~ /(\d\d?) (\d{1,2}) (\d{4}) (\d\d):(\d\d) *- uur/ ) {
    	return ( "$3-$2-$1 $4:$5:00", "$3-$2-$1 $4:".($5+30).":00" );
    }
}


# Find the available channels.  The new site does have a full list of
# channels, which we can freely fetch.
#
sub get_channels() {
    my %channels;

    # Download the full list
    my $url = 'http://www.tvgids.nl/json/lists/channels.php';

    my $chs = get_nice_json($url, '', 1);
    foreach (@{$chs}) {
        $channels{ $_->{'id'} } = { 'name' => $_->{'name'}, 'url' => 'http://tvgidsassets.nl/iphone/channels/big/'.$_->{'id'}.'b.png' };
    }	

    return %channels;
}


# Fetch & process a day's schedules for a channel
sub get_programmes( $$$ ) {

    my ($url, $ch_xid, $ch_id) = @_;
    die if not defined $url; die if ref $url;

    local $SIG{__WARN__} = sub {
    	warn "$url: $_[0]";
    };
    
    local $SIG{__DIE__} = sub {
    	die "$url: $_[0]";
    };

    #print STDERR "Fetching ",$url," ...\n" if not $opt_quiet;

    my $t = get_nice_json($url, '', 1);
    if ( not $t->{ $ch_id }) {
    	warn 'did not find any programmes in page' if not $opt_quiet;
    	return ();
    }

    # fetch each programme from the JSON object
    #
    # some channels return an array   { "2" : [{},{}] }
    # whereas other return a hash!    { "3" : { "0" : {}, "1" : {} } }
    #
    my @progs_to_process;
		
    if ( ref $t->{ $ch_id } eq 'HASH' ) {
        @progs_to_process = @{ $t->{ $ch_id } }{ sort { $a <=> $b } keys %{ $t->{ $ch_id } } };
    } elsif ( ref $t->{ $ch_id } eq 'ARRAY' ) {
        @progs_to_process = @{ $t->{ $ch_id } };
    } else {
        die "unknown type of reply object ".ref $t->{ $ch_id };
    }

    PROG:
    foreach my $_p (@progs_to_process) {
        # e.g.
        #{
        #  "db_id": "16291308",
        #  "titel": "De Wereld Draait Door",
        #  "genre": "Informatief",
        #  "soort": "Talkshow",
        #  "kijkwijzer": "",
        #  "artikel_id": null,
        #  "artikel_titel": null,
        #  "artikel_tekst": null,
        #  "artikel_foto": null,
        #  "datum_start": "2014-04-29 19:00:00",
        #  "datum_end": "2014-04-29 20:00:00"
        #},
        #{
        #  'db_id' => '16387388',
        #  'titel' => "NOS UEFA Champions League Live, Chelsea - Atl\x{e9}tico Madrid",
        #  'genre' => 'Sport',
        #  'soort' => 'Voetbal',
        #  'kijkwijzer' => '',
        #  'artikel_id' => '64576',
        #  'artikel_titel' => 'Chelsea jaagt op derde cup op rij',
        #  'artikel_tekst' => 'Na een ultraverdedigende 0-0-wedstrijd in Madrid mag Chelsea in eigen huis proberen Atl&eacute;tico Madrid te verslaan. Winst is namelijk genoeg voor een plek in de finale van de Champions League.',
        #  'artikel_foto' => 'mourinho_madrid_320.jpg',
        #  'datum_start' => '2014-04-30 20:40:00',
        #  'datum_end' => '2014-04-30 22:45:00',
        #  'is_highlight' => '1'
        #};
    
    
        # Grab data into a hash for this programme
        my $p;
        $p->{'channel'}     = $ch_xid;
        $p->{'title'}       = $_p->{'titel'};
        $p->{'db_id'}       = $_p->{'db_id'};
		
        # calc TZ offset for this programme
        my $tz = DateTime->from_epoch( epoch=>str2time( $_p->{'datum_start'}, 'GMT' ), time_zone=>'Europe/Amsterdam' )->strftime('%z');

        $p->{'start_epoch'} = str2time($_p->{'datum_start'}, $tz);
        $p->{'stop_epoch'}  = str2time($_p->{'datum_end'}, $tz);    
        $p->{'start'}       = time2str( "%Y%m%d%H%M%S %z", $p->{'start_epoch'}, $tz );
        $p->{'stop'}        = time2str( "%Y%m%d%H%M%S %z", $p->{'stop_epoch'}, $tz );

        #print STDERR "$tz : $p->{'start_epoch'} \n";
    	
        push @{$p->{'genres'}}, trim( $_p->{'genre'} )  if ($_p->{'genre'} ne '');  # (e.g. Film) - put before soort
        push @{$p->{'genres'}}, trim( $_p->{'soort'} )  if ($_p->{'soort'} ne '');
			
        $p->{'url'}         = "http://www.tvgids.nl/programma/".$p->{'db_id'};
	
			
        # is the start time within range of this grab?
        next  if ( $p->{'start_epoch'} < $grab_start || $p->{'start_epoch'} >= $grab_end );
	

        # if user wants details then get them from the programme page
        if ($opt_slow) {
            process_details_page ( \$p );
    	}

        # de-dupe the categories
        @{ $p->{'genres'} } = dedupepreserve ( @{ $p->{'genres'} } );
       

        # Reformat the data to create the data structure for the programme
        my $p_out = {};
        $p_out->{'channel'} 	= $p->{'channel'};
        $p_out->{'title'} 		= [[ encode($ENCODING, $p->{'title'}), $LANG ]];
        $p_out->{'start'} 		= $p->{'start'};
        $p_out->{'stop'} 		= $p->{'stop'}  if (defined $p->{'stop'} && $p->{'stop'} ne '');
        $p_out->{'desc'} 		= [[ encode($ENCODING, $p->{'desc'}), $LANG ]]  if (defined $p->{'desc'} && $p->{'desc'} ne '');
        $p_out->{'sub-title'} 	= [[ encode($ENCODING, $p->{'sub_title'}), $LANG ]]  if (defined $p->{'sub_title'} && $p->{'sub_title'} ne '');

        $p_out->{'date'} 		= $p->{'year'}  if (defined $p->{'year'} && $p->{'year'} ne '');

        $p_out->{'rating'} 		= [[ $p->{'rating'} ]]  if (defined $p->{'rating'} && $p->{'rating'} ne '');
        push @{ $p_out->{'rating'}[0] }, ( undef, [{'src' => $p->{'rating_icon'}}] )  if (defined $p->{'rating_icon'} && $p->{'rating_icon'} ne '');
		
        $p_out->{'url'} 	  	= [ encode($ENCODING, $p->{'url'}) ]  if (defined $p->{'url'} && $p->{'url'} ne '');
        $p_out->{'video'}->{'aspect'} = '16:9'  if (defined $p->{'widescreen'} && $p->{'widescreen'} == 1);
	
        # encode the 'credits'
        @{ $p->{'directors'} } = map { encode($ENCODING, trim $_) }  @{ $p->{'directors'} }  if defined $p->{'directors'};
        @{ $p->{'actors'} }    = map { encode($ENCODING, trim $_) }  @{ $p->{'actors'} }     if defined $p->{'actors'};
        $p_out->{'credits'}{'director'} = $p->{'directors'}  if (defined $p->{'directors'} && scalar $p->{'directors'});
        $p_out->{'credits'}{'actor'}    = $p->{'actors'}     if (defined $p->{'actors'}    && scalar $p->{'actors'});
	

        push @{ $p_out->{'title'} }, [ encode($ENCODING, $p->{'original_title'}) ]  if (defined $p->{'original_title'} && $p->{'original_title'} ne '');  # original title is not Dutch!

        # any extra description?
        push @{ $p_out->{'desc'} }, [ encode($ENCODING, $p->{'desc_add'}), $LANG ]  if (defined $p->{'desc_add'} && $p->{'desc_add'} ne '');

    
        if ( scalar @{ $p->{'genres'} } ) {
            foreach (@{ $p->{'genres'} }) {
                push @{ $p_out->{'category'} }, [ encode($ENCODING, $_), $LANG ]  if ($_ ne '');
	    }
  	}


        # store the programme avoiding duplicates
        # also check for duplicate start times and set clumpidx
        {
            if ( defined $programmes->{ $ch_id }->{ $p->{'start_epoch'} } ) {
                # duplicate prog or contemporary?
                my $dup = 0; my $_P;
                foreach $_P ( @{ $programmes->{ $ch_id }->{ $p->{'start_epoch'} } } ) {
                    $dup = 1  if ( $_P->{'title'}[0][0] eq $p_out->{'title'}[0][0] );	# duplicate
    	}
                next PROG if $dup;	# ignore duplicates (go to next programme)
                if (!$dup) { 
                    # contemporary programme so set clumpidx
                    my $numclumps = scalar @{ $programmes->{ $ch_id }->{ $p->{'start_epoch'} } }  + 1;
                    # set (or adjust) clumpidx of existing programmes
                    my $i = 0;
                    foreach $_P ( @{ $programmes->{ $ch_id }->{ $p->{'start_epoch'} } } ) {
                        $_P->{'clumpidx'} = "$i/$numclumps";
                        $i++;
	    }
                    # set clumpidx for new programme
                    $p_out->{'clumpidx'} = "$i/$numclumps";
	    }
	    }
  	}

        # store the programme
        push @{ $programmes->{ $ch_id }->{ $p->{'start_epoch'} } }, $p_out;
	    }
    
	}

# Fetch and parse an individual programme information page
sub process_details_page( $ ) {
    my ($p) = @_;

    my $url = $$p->{'url'};
	
    local $SIG{__WARN__} = sub {
    	warn "$url: $_[0]" unless (defined $_[0] && $_[0] =~ /^Parsing of undecoded UTF-/);
    };

    # Get HTML::TreeBuilder object.
    my $t;
    #       eval { $t = get_nice_tree $url, \&tidypage };
    #
    # page is "charset=iso-8859-1" but sometimes contains UTF-8 !
		#
		# website has changed 2015-06-23 - now requires a session cookie for opt-in to storing cookies. Adding the GET param fixes most of the
		# detail pages but doesn't fix the 302 redirects. Creating a cookiejar (with or without a preset 'cookieoptin' cookie) doesn't fix this which is odd.
		# So we still end up with a few WARN messages for 'did not see 'prog-content' element' when the details page is 302'd to a different URI.
    $t = get_nice_tree($url . '?cookieoptin=true');
    if ($@) {
    	warn "error getting/parsing $url: $@" if not $opt_quiet;
    	return;
    }

    # description is in <p> elements in <div id="prog-content"> (note: there may be >1)
    my $_div = $t->look_down('_tag' => 'div', 'id' => 'prog-content');
    if (not $_div) {
    	warn "did not see 'prog-content' element, skipping page" if not $opt_quiet;
    	return;
    }
    {
        if ( my $_p = $_div->look_down('_tag' => 'p') ) {
            if ( my $_s = $_p->look_down('_tag' => 'span', 'class' => qr/articleblock/ ) ) {
                # are there ever >1 genres here?
                push @{$$p->{'genres'}}, ( ucfirst(lc( trim( $_s->as_text() ) )) );
                $_s->detach();
            }
            $$p->{'desc'} = trim( tidy( $_p->as_text() ) );
            $_p->detach();
        }
        # see if there's any more
        if ( my $_p = $_div->look_down('_tag' => 'p') ) {
            my $html = $_p->as_HTML();
            $html =~ s/(<br>|<br \/>)/ /sg;    # insert spaces between paragraphs
            $html =~ s/<.+?>//sg;              # dump the html
            $$p->{'desc_add'} = trim( tidy( $html ) );
        }
    }
    
    # get the programme details
    $_div = $t->look_down('_tag' => 'div', 'class' => 'programmering_details');
    if (not $_div) {
        warn "did not see 'programmering_details' element, skipping" if not $opt_quiet;
        return;
    }
    {
        if ( my $_ul = $_div->look_down('_tag' => 'ul') ) {
            my @_li = $_ul->look_down('_tag' => 'li');
            #
            # DEPRECATED
            # e.g.
            #     <li><strong>Titel:</strong>Elysium</li>
            #     <li><strong>Zender:</strong>HBO 1</li>
            #     <li><strong>Datum:</strong>29 april 2014</li>
            #     <li><strong>Uitzendtijd:</strong>18:40 - 20:30 uur</li>
            #     <li><strong>Genre:</strong>Film</li>
            #
            foreach my $_li (@_li) {
                my $li = tidy( $_li->as_text() );
                
                if ( $li =~ /Genre:(.*)/ ) {
                    push @{$$p->{'genres'}}, $1;
                }
    
                if ( $li =~ /Orginele titel:(.*)/ ) {
                    $$p->{'original_title'} = $1;
                }
            }
        }
    }
        
    $_div = $t->look_down('_tag' => 'div', 'class' => 'programmering_info_detail');
    if (not $_div) {
        warn "did not see 'programmering_info_detail' element, skipping" if not $opt_quiet;
        return;
    }
    { 
        if ( my $_ul = $_div->look_down('_tag' => 'ul') ) {
            my @_li = $_ul->look_down('_tag' => 'li');
            #
            # DEPRECATED
            # e.g.
            #     <li><strong>Jaar van premiere:</strong>2013</li>
            #     <li><strong>Regisseur:</strong>Neill Blomkamp</li>
            #     <li><strong>Scenario schrijver:</strong>Neill Blomkamp</li>
            #     <li><strong>Componist:</strong>Ryan Amon, Kristian Bailey, Craig Berkey, Hennie Britton, Ricardo Cabrera, Michelle Child</li>
            #     <li><strong>Bijzonderheden:</strong>Breedbeeld uitzending</li>
            #     <li><strong>Acteurs:</strong>Matt Damon, Jodie Foster, Sharlto Copley, Alice Braga, Diego Luna</li>
            #     <li><img src="http://tvgidsassets.nl/img/kijkwijzer/16_transp.png" alt="Niet voor personen tot 16 jaar"></li>
            #
            foreach my $_li (@_li) {
                my $li = tidy( $_li->as_text() );

                if ( $li =~ /Jaar.*:(.*)/ ) {
                    $$p->{'year'} = $1;
                    next;
                }
                
                if ( $li =~ /Regisseur.*:(.*)/ ) {
                    @{ $$p->{'directors'} } = split(/,/, $1);
                    next;
                }
                
                if ( $li =~ /Acteurs.*:(.*)/ ) {
                    @{ $$p->{'actors'} } = split(/,/, $1);
                    next;
                }

                if ( $li =~ /Bijzonderheden:.*Breedbeeld.*/i ) {
                    $$p->{'widescreen'} = 1;
                }

                if ( my $_img = $_li->look_down('_tag' => 'img') ) {
                    my $src = $_img->attr('src');
                    if ( $src =~ /kijkwijzer\/(AL|\d{0,2})_/i ) {     # e.g. 16_transp.png, Kijkwijzer system has AL,6,9,12,16
                        $$p->{'rating'} = uc($1);
                        $$p->{'rating_icon'} = $src;
                    }
                }
            }
        }
    }

}

# Parse date strings that are in Dutch.  'Why not just call
# Date_Init("Language=Dutch")?' I hear you ask.  The trouble is that
# Date::Manip's language is a global setting and having set it to
# Dutch we cannot use code that expects English - either in this file
# or in any libraries.  The least insane way to proceed is to turn
# Dutch to English strings here.
#
# The conversions to make, however, are swiped from the Date::Manip
# code.
#
sub parse_dutch_date( $ ) {
    for (my $tmp = $_[0]) {
	s/\bjanuari\b/January/i;
	s/\bjan\b/January/i;
	s/\bfebruari\b/February/i;
	s/\bfeb\b/February/i;
	s/\bmaart\b/March/i;
	s/\bmaa\b/March/i;
	s/\bmrt\b/March/i;
	s/\bapril\b/April/i;
	s/\bapr\b/April/i;
	s/\bmei\b/May/i;
	s/\bmei\b/May/i;
	s/\bjuni\b/June/i;
	s/\bjun\b/June/i;
	s/\bjuli\b/July/i;
	s/\bjul\b/July/i;
	s/\baugustus\b/August/i;
	s/\baug\b/August/i;
	s/\bseptember\b/September/i;
	s/\bsep\b/September/i;
	s/\boctober\b/October/i;
	s/\boktober\b/October/i;
	s/\boct\b/October/i;
	s/\bokt\b/October/i;
	s/\bnovember\b/November/i;
	s/\bnov\b/November/i;
	s/\bdecember\b/December/i;
	s/\bdec\b/December/i;

	s/\bZondag\b/Sunday/gi;
	s/\bMaandag\b/Monday/gi;
	s/\bDinsdag\b/Tuesday/gi;
	s/\bWoensdag\b/Wednesday/gi;
	s/\bDonderdag\b/Thursday/gi;
	s/\bVrijdag\b/Friday/gi;
	s/\bZaterdag\b/Saturday/gi;

	my $r;
	eval { $r = parse_local_date($_, $TZ) };
	die "could not parse date $_ (from Dutch $_[0])"
	  if $@;
	return $r;
    }
}

# Get the user's home directory
sub get_default_dir {
    my $winhome = $ENV{HOMEDRIVE} . $ENV{HOMEPATH} 
			if defined( $ENV{HOMEDRIVE} ) 
					and defined( $ENV{HOMEPATH} ); 
    
    my $home = $ENV{HOME} || $winhome || ".";
    return $home;
}
 	  	 
# Set default cache dir = $HOME/.xmltv/cache
sub get_default_cachedir {
    return get_default_dir() . "/.xmltv/cache";
}
