This file is indexed.

/usr/bin/tv_grab_fi_sv is in xmltv-util 0.5.70-1.

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

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
#!/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

my $_version = '$Id: tv_grab_fi_sv,v 1.19 2017/09/12 06:09:11 knowledgejunkie Exp $';

use strict;
use warnings;
use utf8;

use DateTime;
use Encode;
use HTML::TreeBuilder;
use IO::Scalar;
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) = $_version =~ qr/$GRABBER_NAME,v ([\d\.]*) /;
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 => $_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",
    );
}