#!/usr/bin/perl

=pod

=head1 NAME

tv_grab_fi_sv - Grab TV listings for Finland in Swedish.

=head1 SYNOPSIS

tv_grab_fi_sv --help

tv_grab_fi_sv --version

tv_grab_fi_sv --capabilities

tv_grab_fi_sv --description

tv_grab_fi_sv [--config-file FILE]
              [--days N] [--offset N]
              [--output FILE] [--quiet] [--debug]

tv_grab_fi_sv --configure [--config-file FILE]

tv_grab_fi_sv --configure-api [--stage NAME]
              [--config-file FILE] [--output FILE]

tv_grab_fi_sv --list-channels [--config-file FILE]
              [--output FILE] [--quiet] [--debug]

=head1 DESCRIPTION

Retrieves and displays TV listings for the Finnish YLE channels plus some of
the most popular commercial channels. The data comes from www.yle.fi and the
Swedish listings are retrieved rather than the Finnish. Just like tv_grab_fi,
this grabber relies on parsing HTML so it could very well stop working at any
time. You have been warned.

=head1 OPTIONS

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

B<--version> Show the versions of the XMLTV libraries, the grabber and of
key modules used for processing listings.

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

B<--description> Show a brief description of the grabber.

B<--config-file FILE> Specify the name of the configuration file to use.
If not specified, a default of B<~/.xmltv/tv_grab_fi_sv.conf> is used.  This
is the file written by B<--configure> and read when grabbing.

B<--output FILE> When grabbing, write output to FILE rather than to standard
output.

B<--days N> When grabbing, grab N days of data instead of all available.
Supported values are 1-14. Default: 14

B<--offset N> Start grabbing at today + N days. Supported values are 0-13.
Default: 0

=head1 SEE ALSO

L<xmltv(5)>.

=head1 AUTHOR

Per Lundberg, (perlun at gmail dot com). Inspired/based on other grabbers,
like tv_grab_uk_rt, tv_grab_se_swedb and tv_grab_fi.

=cut

use strict;
use warnings;
use utf8;

use DateTime;
use Encode;
use HTML::TreeBuilder;
use IO::Scalar;
use XMLTV;
use XMLTV::Ask qw/say/;
use XMLTV::Configure::Writer;
use XMLTV::Get_nice 0.005070;
use XMLTV::Memoize;
use XMLTV::Options qw/ParseOptions/;

sub t;

# Constants.
# my $DATA_SITE_ROOT  = 'https://areena.yle.fi/'; # Finnish
my $DATA_SITE_ROOT  = 'https://arenan.yle.fi/';   # Swedish
my $GRABBER_NAME    = 'tv_grab_fi_sv';
my $GRABBER_VERSION = "$XMLTV::VERSION";
my $XML_ENCODING    = 'utf-8';
my $LANGUAGE_CODE   = 'sv';

# This is not the timezone for the machine on which the grabber is
# being run, but rather the timezone in which all the grabbed data is
# being specified.
my $TIMEZONE = 'Europe/Helsinki';

# Attributes of the root element in output.
my $xmltv_attributes =
{
    'source-info-url'     => 'http://www.yle.fi/',
    'source-data-url'     => "$DATA_SITE_ROOT/",
    'generator-info-name' => "XMLTV/$XMLTV::VERSION, $GRABBER_NAME $GRABBER_VERSION",
    'generator-info-url'  => 'http://www.xmltv.org',
};

XMLTV::Memoize::check_argv('XMLTV::Get_nice::get_nice_aux');

# The list of channels available from the Yle Program Guide. Their
# names are deliberately specified in a manner which would be natural
# for people watching e.g. TV channels from Sweden (so that "TV1"
# would in their mindset not necessarily refer to Yle's TV1 channel -
# thus, the reason behind the "Yle" prefixing here).
#
# The key in this hash is the name of the channel as given on the Yle
# program guide web page.
my $channels =
{
    'tv1.yle.fi' => {
        'id' => 'tv1.yle.fi',
        'display-name' => [[ 'YLE TV1', $LANGUAGE_CODE ]]
    },
    'tv2.yle.fi' => {
        'id' => 'tv2.yle.fi',
        'display-name' => [[ 'YLE TV2', $LANGUAGE_CODE ]]
    },
    'teemafem.yle.fi' => {
        'id' => 'teemafem.yle.fi',
        'display-name' => [[ 'YLE TEEMA/FEM', $LANGUAGE_CODE ]]
    },
    'areena.yle.fi' => {
        'id' => 'areena.yle.fi',
        'display-name' => [[ 'AREENA', $LANGUAGE_CODE ]]
    },
    'mtv3.yle.fi' => {
        'id' => 'mtv3.yle.fi',
        'display-name' => [[ 'MTV3', $LANGUAGE_CODE ]]
    },
    'nelonen.yle.fi' => {
        'id' => 'nelonen.yle.fi',
        'display-name' => [[ 'NELONEN', $LANGUAGE_CODE ]]
    },
    'sub.yle.fi' => {
        'id' => 'sub.yle.fi',
        'display-name' => [[ 'SUB', $LANGUAGE_CODE ]]
    },
    'tv5.yle.fi' => {
        'id' => 'tv5.yle.fi',
        'display-name' => [[ 'TV5', $LANGUAGE_CODE ]]
    },
    'liv.yle.fi' => {
        'id' => 'liv.yle.fi',
        'display-name' => [[ 'LIV', $LANGUAGE_CODE ]]
    },
    'jim.yle.fi' => {
        'id' => 'jim.yle.fi',
        'display-name' => [[ 'JIM', $LANGUAGE_CODE ]]
    },
    'kutonen.yle.fi' => {
        'id' => 'kutonen.yle.fi',
        'display-name' => [[ 'KUTONEN', $LANGUAGE_CODE ]]
    },
    'tlc.yle.fi' => {
        'id' => 'tlc.yle.fi',
        'display-name' => [[ 'TLC', $LANGUAGE_CODE ]]
    },
    'fox.yle.fi' => {
        'id' => 'fox.yle.fi',
        'display-name' => [[ 'FOX', $LANGUAGE_CODE ]]
    },
    'ava.yle.fi' => {
        'id' => 'ava.yle.fi',
        'display-name' => [[ 'AVA', $LANGUAGE_CODE ]]
    },
    'hero.yle.fi' => {
        'id' => 'hero.yle.fi',
        'display-name' => [[ 'HERO', $LANGUAGE_CODE ]]
    },
    'alfatv.yle.fi' => {
        'id' => 'alfatv.yle.fi',
        'display-name' => [[ 'ALFATV', $LANGUAGE_CODE ]]
    },
    'frii.yle.fi' => {
        'id' => 'frii.yle.fi',
        'display-name' => [[ 'FRII', $LANGUAGE_CODE ]]
    },
    'natgeo.yle.fi' => {
        'id' => 'natgeo.yle.fi',
        'display-name' => [[ 'NATIONAL GEOGRAPHIC', $LANGUAGE_CODE ]]
    },
    'tvfinland.yle.fi' => {
        'id' => 'tvfinland.yle.fi',
        'display-name' => [[ 'TV FINLAND', $LANGUAGE_CODE ]]
    },
};

# Map between channel names (as presented by the YLE data) and channel
# IDs, as created by us.
my $channel_id_map =
{
    'yle-tv1' => 'tv1.yle.fi',
    'yle-tv2' => 'tv2.yle.fi',
    'yle-teema-fem' => 'teemafem.yle.fi',
    'yle-areena' => 'areena.yle.fi',
    'mtv3' => 'mtv3.yle.fi',
    'nelonen' => 'nelonen.yle.fi',
    'sub' => 'sub.yle.fi',
    'tv5' => 'tv5.yle.fi',
    'liv' => 'liv.yle.fi',
    'jim' => 'jim.yle.fi',
    'kutonen' => 'kutonen.yle.fi',
    'tlc' => 'tlc.yle.fi',
    'fox' => 'fox.yle.fi',
    'ava' => 'ava.yle.fi',
    'hero' => 'hero.yle.fi',
    'alfatv' => 'alfatv.yle.fi',
    'frii' => 'frii.yle.fi',
    'national-geographic' => 'natgeo.yle.fi',
    'tv-finland' => 'tvfinland.yle.fi',
};

my @ARGUMENTS = @ARGV;

# Parse the standard XMLTV grabber options.
my ($opt, $conf) = ParseOptions(
{
    grabber_name => "tv_grab_fi_sv",
    capabilities => [qw/baseline manualconfig apiconfig/],
    stage_sub => \&config_stage,
    listchannels_sub => \&list_channels,
    version => $GRABBER_VERSION,
    description => "Finland (Swedish)",
    defaults => { days => 14, offset => 0, quiet => 0, debug => 0 },
});

t("Command line arguments: " . join(' ', @ARGUMENTS));

# When we get here, we know that we are invoked in such a way that the
# channel data should be grabbed.

# Configure the output and write the XMLTV data - header, channels,
# listings, and footer
my $writer;
setup_xmltv_writer();
write_xmltv_header();
write_channel_list(@{ $conf->{channel} });
write_listings_data(@{ $conf->{channel} });
write_xmltv_footer();

# For the moment, we always claim that we've exited successfully...
exit 0;

sub t
{
    my $message = shift;
    print STDERR $message . "\n" if $opt->{debug};
}

sub config_stage
{
    my($stage, $conf) = shift;

    die "Unknown stage $stage" if $stage ne "start";

    # This grabber doesn't need any configuration (except for
    # possibly channel, selection), so this subroutine doesn't need
    # to do very much at all.
    my $result;
    my $writer = new XMLTV::Configure::Writer(OUTPUT => \$result,
        encoding => $XML_ENCODING);
    $writer->start({ grabber => 'tv_grab_fi_sv' });
    $writer->end('select-channels');

    return $result;
}

# Returns a string containing an xml-document with <channel>-elements
# for all available channels.
sub list_channels
{
    my ($conf, $opt) = shift;

    my $result = '';
    my $fh = new IO::Scalar \$result;
    my $oldfh = select($fh);

    # Create an XMLTV::Writer object. The important part here is that
    # the output should go to $fh (in other words, to the $result
    # string), NOT to stdout...
    my %writer_args =
    (
        encoding => $XML_ENCODING,
        OUTPUT => $fh
    );

    my $writer = new XMLTV::Writer(%writer_args);
    $writer->start($xmltv_attributes);

    # Loop over all channels and write them to this XMLTV::Writer.
    foreach my $channel_id (keys %{ $channels })
    {
        my $channel = $channels->{$channel_id};
        $writer->write_channel($channel);
    }

    $writer->end;

    select($oldfh);
    $fh->close();

    return $result;
}

# Determine options for XMLTV::Writer, and instantiate it.
sub setup_xmltv_writer
{
    # output options
    my %g_args = ();
    if (defined $opt->{output})
    {
        t("\nOpening XML output file '$opt->{output}'\n");
        my $fh = new IO::File ">$opt->{output}";
        die "Error: Cannot write to '$opt->{output}', exiting" if (!$fh);
        %g_args = (OUTPUT => $fh);
    }

    # Determine how many days of listings are required and
    # range-check, applying default values if necessary. If --days or
    # --offset is specified we must ensure that the values for days,
    # offset and cutoff are passed to XMLTV::Writer.
    my %d_args = ();
    if (defined $opt->{days} || defined $opt->{offset})
    {
        if (defined $opt->{days})
        {
            if ($opt->{days} < 1 || $opt->{days} > 14)
            {
                if (!$opt->{quiet})
                {
                    say("Specified --days option is not possible (1-14). " .
                        "Retrieving all available listings.");
                }
                $opt->{days} = 14
            }
        }
        else
        {
            # No --days parameter were given. Use the default.
            $opt->{days} = 14;
        }

        if (defined $opt->{offset})
        {
            if ($opt->{offset} < 0 || $opt->{offset} > 13)
            {
                if (!$opt->{quiet})
                {
                    say("Specified --offset option is not possible (0-13). "
                        . "Retrieving all available listings.");
                }
                $opt->{offset} = 0;
            }
        }
        else
        {
            $opt->{offset} = 0;
        }

        $d_args{days} = $opt->{days};
        $d_args{offset} = $opt->{offset};
        $d_args{cutoff} = "000000";
    }

    t("Setting up XMLTV::Writer using \"" . $XML_ENCODING . "\" for output");
    $writer = new XMLTV::Writer(%g_args, %d_args, encoding => $XML_ENCODING);
}

# Writes the XMLTV header.
sub write_xmltv_header
{
    t("Writing XMLTV header");
    $writer->start($xmltv_attributes);
}

# Writes the channel list for all configured channels
sub write_channel_list
{
    my (@channels) = @_;

    t("Started writing <channel> elements");
    foreach my $channel_id (sort @channels)
    {
        my $channel = $channels->{$channel_id};
        $writer->write_channel($channel);
    }
    t("Finished writing <channel> elements");
}

# Download listings data for all the configured channels
sub write_listings_data
{
    my (@channels) = @_;

    my $programmes = {};
    my $previous_programmes = {};

    say(scalar @channels ." configured channels")  if !$opt->{quiet};

    my $dt_today = DateTime->today( time_zone => $TIMEZONE );
    say("     Today: " . $dt_today->strftime( '%Y-%m-%dT%H:%M:%S %z')) if $opt->{debug};

    # Get start & stop times for the grab
    my $dt_grab_start = $dt_today->clone->add( days => $opt->{offset} );
    say("Grab start: " . $dt_grab_start->strftime( '%Y-%m-%dT%H:%M:%S %z')) if $opt->{debug};

    my $dt_grab_stop  = $dt_grab_start->clone->add( days => $opt->{days} );
    say(" Grab stop: " . $dt_grab_stop->strftime( '%Y-%m-%dT%H:%M:%S %z')) if $opt->{debug};

    # schedules run from 06:00-06:00 so to pass tv_validate_file we need
    # to get the day before also
    DAY:
    for (my $i = $opt->{offset} - 1; $i < $opt->{offset} + $opt->{days}; $i++)
    {
        # Create URL for the schedules for this channel/month/day combination.
        # e.g. https://areena.yle.fi/tv/guide?t=2017-09-08
        my $date = $dt_today->clone->add( days => $i );
        my $url = sprintf('%stv/guide?t=%s', $DATA_SITE_ROOT, $date->strftime( '%Y-%m-%d' ));

        say("Downloading $url") if $opt->{debug};

        # The yle website does not parse correctly via HTML::TreeBuilder unless
        # we accept it as-is, hence $t->implicit_tags(0)
        my $htb_opts = { 'implicit_tags' => '0', 'ignore_unknown' => '0', };
        my $tree  = get_nice_tree($url, undef, undef, $htb_opts);

        my @t_channels = $tree->look_down('_tag' => 'li', 'class' => 'guide-channels__channel');
        say '  Found '.scalar @t_channels.' channels' if $opt->{debug};
        next DAY if scalar @t_channels == 0;

        # Can't use foreach because of clumpidx processing below
        CHANNEL:
        for (my $j = 0; $j < scalar @t_channels; $j++)
        {
            my $t_channel = $t_channels[$j];

            my $chan_id_raw = $t_channel->look_down('_tag' => 'div')->attr('aria-label');
            my $chan_id = lc (join ('-', split (' ', $chan_id_raw)) );

            # Check if this program belongs to one of the
            # configured channels.  If it doesn't, ignore it.
            say "    Found $chan_id" if $opt->{debug};
            my $c_channel_id = $channel_id_map->{$chan_id};

            if (!$c_channel_id)
            {
                say "    UNKNOWN CHANNEL ID $chan_id, skipping" if $opt->{debug};
                next CHANNEL;
            }

            say "    Processing $c_channel_id" if $opt->{debug};

            my $t_schedule = $t_channel->look_down('_tag' => 'ul', 'class' => 'schedule-list');
            my @t_progs = $t_schedule->look_down('_tag' => 'li', 'class' => qr/schedule-card/);
            say "      Found " . scalar @t_progs . " programmes" if $opt->{debug};

            PROGRAMME:
            foreach my $t_prog (@t_progs)
            {
                my ($t_prog_label, $t_prog_desc, $t_prog_link, $t_prog_title, $t_prog_film);
                my ($p_start, $e_start, $p_end, $p_dtstart, $p_dtend);
                my ($p_title, $p_subtitle, $p_desc, $p_url, $p_category, $p_rating);
                my ($p_season, $p_episode_num, $p_episode_total, $p_part_num, $p_number);

                $t_prog_label = $t_prog->look_down('_tag' => 'span', 'itemprop' => 'name');
                next PROGRAMME unless $t_prog_label;
                $p_title = $t_prog_label->as_text();
                say "        Processing title: " . $p_title if $opt->{debug};

                # Extract film category from title
                if ($p_title =~ s/^(Film|Ny film|Elokuva):\s*//)
                {
                    $p_category = $1;
                }

                # Extract rating details
                if ($p_title =~ s/\s*\((S|T|7|12|16|18)\)$//)
                {
                    $p_rating = $1;
                }
                # Extract season number from title if present
                if ($p_title =~ s/\s(\d+)\.\skausi//i)
                {
                    $p_season = $1;
                }

                $t_prog_desc = $t_prog->look_down('_tag' => 'span', 'itemprop' => 'description');

                # Extract possible sub-title/season/episode numbering from description
                # Try to handle both Finnish and Swedish versions
                if ($t_prog_desc)
                {
                    $p_desc = $t_prog_desc->as_text();

                    # Extract rating details from desc
                    if ($p_desc =~ s/^\((S|T|7|12|16|18)\)\.\s*//)
                    {
                        $p_rating = $1;
                    }

                    # Remove/update new season text before processing
                    for ($p_desc)
                    {
                        $_ =~ s/^Sarja alkaa\.\s*//i;
                        $_ =~ s/^Sarja alkaa uusintana\.\s*//i;
                        $_ =~ s/^Sarja alkaa alusta uusintana\.\s*//i;
                        $_ =~ s/^(\d+)\. kausi alkaa uusintana. Osa (\d+)\./Kausi $1. Osa $2./i;
                        $_ =~ s/^Kausi (\d+) \w+\. (\d+)\/(\d+)\./Kausi $1. Osa $2\/$3./i;
                        $_ =~ s/^(\d+)\. tuotantokausi, (\d+)\/(\d+)/Kausi $1, $2\/$3/i;
                        $_ =~ s/^Sarja alkaa, (?:osa)? (\d+)\/(\d+)/Kausi 1, $1\/$2/i;
                        $_ =~ s/^Uusi kausi\!\s*//i;
                        $_ =~ s/^Uusi sarja\!\s*//i;
                    }

                    # Extract likely sub-title
                    if ($p_desc =~ s/^(.*)\. K?ausi (\d+)/Kausi $2/)
                    {
                        $p_subtitle = $1;
                    }

                    if ($p_desc =~ s/^(?:Kausi|Säsong)\s*(\d+)[.,]\s*(?:Jakso|Avsnitt|Osa|Del)?\s*(\d+)\s*\/?\s*(\d+)?\s*\.//i)
                    {
                        $p_season = $1;
                        $p_episode_num = $2;
                        $p_episode_total = $3;
                    }
                    elsif ($p_desc =~ s/^(?:Kausi|Säsong)\s*(\d+)[.,]\s*(\d+)\s*\/\s*(\d+)\s*(\w)/$4/i)
                    {
                        $p_season = $1;
                        $p_episode_num = $2;
                        $p_episode_total = $3;
                    }
                    elsif ($p_desc =~ s/^(?:Kausi|Säsong)\s*(\d+)[.,]\s*(?:Jakso|Avsnitt)\s*(\d+)[.,]\s*(?:Osa|Del)\s*(\d+)\s*\.//i)
                    {
                        $p_season = $1;
                        $p_episode_num = $2;
                        $p_part_num = $3;
                    }
                    elsif ($p_desc =~ s/^(?:Jakso|Avsnitt|Osa|Del)\s*(\d+)\s*\/?\s*(\d+)?\s*\.//i)
                    {
                        $p_episode_num = $1;
                        $p_episode_total = $2;
                    }
                    elsif ($p_desc =~ s/\. (?:Jakso|Avsnitt|Osa|Del)\s*(\d+)\s*\/?\s*(\d+)?\s*\.?$//i)
                    {
                        $p_episode_num = $1;
                        $p_episode_total = $2;
                    }
                    elsif ($p_desc =~ s/^(?:Jakso|Avsnitt|Osa|Del)\s*(\d+):\s*//i)
                    {
                        $p_episode_num = $1;
                    }

                    # Remove/update new season text after processing
                    for ($p_desc)
                    {
                        $_ =~ s/^\s*Uusi \d+\. kausi\!//i;
                        $_ =~ s/^\s*Uusi kausi\!\s*//i;
                        $_ =~ s/^\s*Uusi sarja\!\s*//i;
                    }
                }

                # FIXME
                # extract cast information from description
                # extract movie year
                # extract original movie title

                # Create correctly-indexed programme season/episode numbering
                #
                # series number is zero-indexed
                if (defined $p_season && $p_season > 0)
                {
                    $p_season--;
                }
                else
                {
                    $p_season = '';
                }
                # episode number is zero-indexed
                if (defined $p_episode_num && $p_episode_num > 0)
                {
                    $p_episode_num--;
                }
                else
                {
                    $p_episode_num = '';
                }
                # episode total is one-indexed and should always be greater than the
                # max episode number (which is zero-indexed)
                if (defined $p_episode_total && $p_episode_total > 0
                                             && $p_episode_total > $p_episode_num )
                {
                    $p_episode_total = "/" . $p_episode_total;
                }
                else
                {
                    $p_episode_total = '';
                }
                # part number is zero-indexed
                if (defined $p_part_num && $p_part_num > 0)
                {
                    $p_part_num--;
                }
                else
                {
                    $p_part_num = '';
                }

                $p_number = "" . $p_season . "."
                               . $p_episode_num . $p_episode_total . "."
                               . $p_part_num;


                # If programme is outside of requested timeframe then drop it
                $p_start = $t_prog->look_down('_tag' => 'time', 'itemprop' => 'startDate')->attr('datetime');
                # say("          StartDate: " . $p_start) if $opt->{debug};
                my $dt_prog_start = dt_from_itempropdate($p_start);
                if ($dt_prog_start < $dt_grab_start  ||  $dt_prog_start >= $dt_grab_stop)
                {
                    # say("       ** Programme starts outside of grabbing window, skipping...\n") if $opt->{debug};
                    next PROGRAMME;
                }

                $p_end = $t_prog->look_down('_tag' => 'time', 'itemprop' => 'endDate')->attr('datetime');
                my $dt_prog_stop = dt_from_itempropdate($p_end);

                $p_dtstart = xmltv_isotime( $p_start );
                $p_dtend   = xmltv_isotime( $p_end );

                # If the previous programme on this channel overlaps with the start time of this programme,
                # trust our start time and update the stop time of the previous programme
                if (exists $previous_programmes->{$c_channel_id}
                       and $previous_programmes->{$c_channel_id}->{'stop'} gt $p_dtstart)
                {
                    say("      ** Overlap detected, updating previous programme's stop time") if !$opt->{quiet};
                    $previous_programmes->{$c_channel_id}->{'stop'} = $p_dtstart;
                }

                $t_prog_link = $t_prog->look_down('_tag' => 'a', 'class' => 'schedule-card__link');
                $p_url = $DATA_SITE_ROOT . $t_prog_link->attr('href') if $t_prog_link;

                # Create the data structure for the program.
                my $programme =
                {
                    'channel' => $c_channel_id,
                    'title'   => [[ encode('utf-8', $p_title), $LANGUAGE_CODE ]],
                    'start'   => $p_dtstart,
                    'stop'    => $p_dtend,
                };
                $programme->{'desc'} = [[ encode('utf-8', tidy( $p_desc) ), $LANGUAGE_CODE ]]  if (defined $p_desc && $p_desc ne '');
                $programme->{'sub-title'} = [[ encode('utf-8', $p_subtitle), $LANGUAGE_CODE ]]  if (defined $p_subtitle && $p_subtitle ne '');
                $programme->{'category'} = [[ encode('utf-8', $p_category) ]]  if (defined $p_category && $p_category ne '');
                $programme->{'url'} = [ $p_url ]  if (defined $p_url && $p_url ne '');
                $programme->{'rating'} = [ [ $p_rating, 'KAVI' ] ] if (defined $p_rating && $p_rating ne '');
                $programme->{'episode-num'} = [ [ $p_number, "xmltv_ns" ] ] if defined $p_number && $p_number ne '..';


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

                # store the programme
                push @{ $programmes->{$c_channel_id}->{$p_dtstart} }, $programme;
                # remember previous programme on this channel to check start/stop overlap
                $previous_programmes->{$c_channel_id} = $programme;
            }
        }
    }


    # All data has been gathered. We can now write the programmes hash to output.
    foreach ( sort keys %{$programmes} )
    {
        my $ch_progs = $programmes->{$_};
        foreach ( sort keys %{$ch_progs} )
        {
            my $dt_progs  = $ch_progs->{$_};
            foreach (@{ $dt_progs })
            {
                $writer->write_programme($_);
            }
        }
    }
}

# Writes the XMLTV footer.
sub write_xmltv_footer
{
    t("\nWriting XMLTV footer\n");
    $writer->end;
}

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

# Trim function to remove whitespace from the start and end of the
# string.
sub trim ($)
{
    my $string = shift;
    $string =~ s/^\s+//;
    $string =~ s/\s+$//;
    return $string;
}

# Converts a DateTime + time of the form "2014-04-12T09:00:00+03:00" to something suitable
# for XMLTV, i.e.  20140412090000 +0300
sub xmltv_isotime ($)
{
    my $time = shift;

    # let's not overthink this... just use a regexp!

    $time =~ s/[:-]//g;
    $time =~ /^(\d{8})T(\d{6}).*(\+\d{4})$/;
    return $1.$2.' '.$3;
}

# Convert a string of the form "2017-09-09T06:00:00+03:00" to a DateTime
sub dt_from_itempropdate
{
    my $date = shift;
    my ($y, $m, $d, $h, $i, $s, $t, $th, $tm) = $date =~ /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})([\+-])(\d{2}):(\d{2})$/;
    return DateTime->new(
        year => $y,
        month => $m,
        day => $d,
        hour => $h,
        minute => $i,
        second => $s,
        time_zone => "$t$th$tm",
    );
}
