This file is indexed.

/usr/bin/tv_grab_is is in xmltv-util 0.5.63-2.

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

=head1 SYNOPSIS

tv_grab_is --help

tv_grab_is [--config-file FILE] --configure [--gui OPTION]

tv_grab_is [--config-file FILE] [--output FILE] [--days N]
           [--offset N] [--quiet]

tv_grab_is --capabilities

tv_grab_is --version

=head1 DESCRIPTION

Output TV listings for several channels available in Iceland. 

First run B<tv_grab_is --configure> to choose, which channels you want
to download. Then running B<tv_grab_is> 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_is.conf>.  This is the file written by
B<--configure> and read when grabbing.

B<--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.

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

B<--days N> Grab N days.  The default is as many as the source carries.

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

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

Yngvi Þór Sigurjónsson (yngvi@teymi.is). Heavily based on
tv_grab_dk by Jesper Skov (jskov@zoftcorp.dk). tv_grab_dk
originally based on tv_grab_nl by Guido Diepen and Ed Avis
(ed@membled.com) and tv_grab_fi by Matti Airas.

Version 1.1, Eggert Thorlacius (eggert@thorlacius.com).  Started out by
replacing a couple of channels with XML feeds, but ended up by removing the
sjonvarp.is code completely.  Left in the "xxx.sjonvarp.is" XMLTV IDs for
backwards compatibility.


=head1 BUGS


=cut
use strict;
use XMLTV::Version '$Id: tv_grab_is,v 1.26 2011/06/22 05:56:34 rmeden Exp $ ';
use XMLTV::Capabilities qw/baseline manualconfig cache/;
use XMLTV::Description 'Iceland';
use Getopt::Long;
use HTML::TreeBuilder;
use HTML::Entities; # parse entities
use IO::File;
use URI;
use utf8; # source code is encoded in utf8

use Date::Manip;
use XML::LibXSLT;
use XML::DOM;

use XMLTV;
use XMLTV::Memoize;
use XMLTV::ProgressBar;
use XMLTV::Ask;
use XMLTV::Mode;
use XMLTV::Config_file;
use XMLTV::DST;
use XMLTV::Get_nice;
use XMLTV::Date;
use XMLTV::Usage <<END
$0: get Icelandic 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]
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();
    }
}

# default language
my $LANG = 'is';


sub basechid($);
sub ispluschannel($);
sub process_xml_channel( $$$$$$ );
sub process_ruv_is( $$$$$$ );
sub process_skjarinn_is( $$$$$$ );
sub process_stod2_and_friends( $$$$$$ );


# Get options
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_days   = 7; # default
$opt_offset = 0; # default
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,
           'list-channels' => \$opt_list_channels,
          )
  or usage(0);
die 'number of days must not be negative'
  if (defined $opt_days && $opt_days < 0);
usage(1) if $opt_help;

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_is', $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: $!";
    # find list of available channels
    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;
    my @chs = sort keys %channels;
    my @names = map { $channels{$_} } @chs;
    my @qs = map { "add channel $_?" } @names;
    my @want = ask_many_boolean(1, @qs);
    foreach (@chs) {
        my $w = shift @want;
        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;
        my $name = shift @names;
        print CONF "channel $_ $name\n";
        # TODO don't store display-name in config file.
    }

    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';

# If we are grabbing, check we can read the config file before doing
# anything else.
#
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} = 'ISO-8859-1';
$w_args{UNSAFE} = 1;    # Needed by process_xml_channel
my $writer = new XMLTV::Writer(%w_args);
# TODO: standardize these things between grabbers.
$writer->start
  ({ 'generator-info-name' => 'XMLTV',
     'generator-info-url'  => 'http://xmltv.org/',
   });

if ($mode eq 'list-channels') {
    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;

    foreach my $ch_did (sort(keys %channels)) {
        my $ch_name = $channels{$ch_did};
        my $ch_xid = "$ch_did.sjonvarp.is";
       $writer->write_channel({ id => $ch_xid,
                                 'display-name' => [ [ $ch_name ] ],
                                 'icon' => [{'src' => get_icon($ch_did)}]
                                });
    }
    $bar->finish() if not $opt_quiet;
    $writer->end();
    exit();
}
# Not configuring or writing channels, must be grabbing listings.
die if $mode ne 'grab';
my (%channels, @channels, $ch_did, $ch_name);
my $line_num = 1;
foreach (@config_lines) {
    ++ $line_num;
    next if not defined;

    # FIXME channel data should be read from the site, and then the
    # config file only gives the XMLTV ids that are interesting.
    #
    # Using internal list of channels now to get correctly encoded
    # channel names. Config file format remains unchanged for compatibility
    #
    if (/^channel:?\s+(\S+)\s+([^\#]+)/) {
    $ch_did = $1;
    push @channels, $ch_did;
    } 
    else {
    warn "$config_file:$.: bad line\n";
    }
}

%channels = get_channels();

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

my $now = parse_date('now');
die if not defined $now;

Date_Init('TZ=UTC');

# Mapping from cannel ID to URL
my %stod2AndFriends = (
    "ST2" => "http://www.stod2.is/XML--dagskrar-feed/XML-Stod-2-dagskra-vikunnar",
    "ST2SPORT" => "http://www.stod2.is/XML--dagskrar-feed/XML-Stod-2-Sport-dagskra-vikunnar",
    "ST2SPORT2" => "http://www.stod2.is/XML--dagskrar-feed/XML-Stod-2-Sport-2-dagskra-vikunnar",
    "ST2SPORT3" => "http://www.stod2.is/XML--dagskrar-feed/XML-Stod-2-Sport-3-dagskra-vikunnar",
    "ST2SPORT4" => "http://www.stod2.is/XML--dagskrar-feed/XML-Stod-2-Sport-4-dagskra-vikunnar",
    "ST2SPORT5" => "http://www.stod2.is/XML--dagskrar-feed/XML-Stod-2-Sport-5-dagskra-vikunnar",
    "ST2SPORT6" => "http://www.stod2.is/XML--dagskrar-feed/XML-Stod-2-Sport-6-dagskra-vikunnar",
    "ST2EXTRA" => "http://www.stod2.is/XML--dagskrar-feed/XML-Stod-2-Extra-dagskra-vikunnar",
    "ST2BIO" => "http://www.stod2.is/XML--dagskrar-feed/XML-Stod-2-Bio-dagskra-vikunnar",
);

# Declare array of { date, num_days, channel_id, channel_xid, function } 
# and populate it with all pages we need to get.  For sites that only
# support getting a single day at a time, we create $opt_days entries
# per channel, but for the others, we create a single entry
my @to_get;

my $startday = UnixDate(DateCalc(UnixDate($now, '%Y-%m-%d'), "+ $opt_offset days"), '%Y-%m-%d'); die if not defined $startday;


foreach $ch_did (@channels) {

    $ch_name = $channels{$ch_did};
    my $ch_xid = "$ch_did.sjonvarp.is";
    $writer->write_channel({ id => $ch_xid,
                 'display-name' => [ [ $ch_name ] ],
                 'icon' => [{'src' => get_icon($ch_did)}]
                 });
    
    my $timeoffset = ispluschannel($ch_did) ? 1 : 0;
    
    if (basechid ($ch_did) eq 'RUV') {
        push @to_get, [ $startday, $opt_days, $ch_did, $ch_xid, $timeoffset, \&process_ruv_is ];
    } elsif (basechid ($ch_did) eq 'S1') {
        push @to_get, [ $startday, $opt_days, $ch_did, $ch_xid, $timeoffset, \&process_skjarinn_is ];
    } elsif (defined ($stod2AndFriends{basechid ($ch_did)} ) ) {
        push @to_get, [ $startday, $opt_days, $ch_did, $ch_xid, $timeoffset, \&process_stod2_and_friends ];
    }
}

my %warned_ch_name; # suppress duplicate warnings

my $bar = new XMLTV::ProgressBar('fetching data', scalar @to_get)
  if not $opt_quiet;
my @to_get_detailed;
my $num_detailed = 0;
foreach (@to_get) {
    my ($date, $num_days, $ch_tvgids_id, $ch_xmltv_id, $timeoffset, $func) = @$_;
     &{$func}($writer, $date, $num_days, $ch_tvgids_id, $timeoffset, $ch_xmltv_id);

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


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

# Attepmts to parse director from a string. If successful, director
# is removed from original string and returned
 
sub get_director($) {
    my $director ="";
    if($_[0] =~ s/Leikstjóri:\s*([^.]*)\.// ) {
        $director = $2;
    }
    return $director;
}

# Attepmts to parse actors from a string. If successful, actor list
# is removed from original string and returned as an array
sub get_actors($) {
    my $actors;
    if($_[0] =~ s/\s*(Aðalhlutverk:|[mM]eðal leikenda eru|Aðalhlutverk leika|[Íí] aðalhutverkum eru|[Ll]eikendur eru)\s*([^.]*)\.// ) {
        my @a = split(/, | og /, $2);
        s/[.]$// foreach @a;
        push @$actors, @a;
    }
    return $actors;
}

# Cuts "plus." of xmlhannelID if appropriate
sub basechid($) {
    my ( $id ) = @_;
    if ($id =~ /^plus./) {
        return substr($id, 5);
    }
    return $id;
}

sub ispluschannel($) {
    return substr($_[0], 0, 5) eq "plus."
}

# Takes XML and XSL transform that converts it to a list of <programme>
# elements, and writes the elements to the XMLTV writer (after massaging them
# a bit)
sub process_xml_channel( $$$$$$ ) {
    my ($writer, $infromdate, $num_days, $timeoffset, $xsl_transform, $xml) = @_;

    my $fromdate = ParseDate($infromdate);
    my $enddate = ParseDate(UnixDate(DateCalc($fromdate, "+ " . ($num_days) . " days"), '%Y-%m-%d'));

    # Step one: Use XSLT to munge XML to XMLTV format...
    my $parser = XML::LibXML->new(); die unless defined $parser;
    my $xslt = XML::LibXSLT->new(); die unless defined $xslt;
    my $stylesheet = $xslt->parse_stylesheet($parser->parse_string($xsl_transform));
    my $results = $stylesheet->transform($parser->parse_string($xml));

    # Step 2: Loop through all programmes and all their children.
    # Do some processing on the children and then dump the programme 
    # into the writer.
    my @programmeElem = $results->getDocumentElement->getElementsByTagName('programme');
    foreach my $programme (@programmeElem) {
        my $myDate = ParseDate($programme->getAttribute('start'));
        if ((Date_Cmp($myDate, $fromdate) >= 0) && (Date_Cmp($myDate, $enddate) < 0)) {
            $myDate = DateCalc($myDate, "+ " . $timeoffset . " hours"); # Add one hour if this is a plus channel
            $myDate = UnixDate($myDate,'%q') . " +0000";   # Convert date to "20081231235900 +0000"
            $programme->setAttribute('start', $myDate);
            
            foreach my $node ($programme->childNodes) {
                if ($node->nodeName eq 'title' && $node->hasChildNodes()) {
                    my $titleStr = $node->firstChild->data;
                    $titleStr =~ s/ - N.TT$//;  # Strip garbage that no one cares about
                    $titleStr =~ s/ - Loka..ttur$//;
                    my $episode_num="$1:$2" if ($titleStr =~ s/\s*\((\d+):(\d+)\)//);
                    if ($episode_num) {
                        my $episodeNode = XML::LibXML::Element->new('episode-num');
                        $episodeNode->appendTextNode($episode_num);
                        $programme->appendChild($episodeNode);
                    }
                    $node->firstChild->setData($titleStr);
                } elsif ($node->nodeName eq 'sub-title' && ( !$node->hasChildNodes()  || ($node->firstChild->data =~ /^[\n ]*$/))) {
                        $programme->removeChild($node);
                } elsif ($node->nodeName eq 'desc') {
                    if ($node->hasChildNodes() && ($node->firstChild->data !~ /^[\n ]*$/)) {
                        my $credits = $programme->find("credits")->get_node(0);
                        if( !defined( $credits ) ) {
                            $credits = XML::LibXML::Element->new( 'credits' );
                            $programme->insertAfter( $credits, $node );
                        }
                        # If this is the description, extract director and actors
                        my $director = get_director($node->firstChild->data);
                        if ($director ne "") {
                            my $dirNode = XML::LibXML::Element->new('director');
                            $dirNode->appendTextNode($director);
                            $credits->appendChild($dirNode);
                        }
                        my $actors = get_actors($node->firstChild->data);
                        foreach my $actor (@$actors) {
                            my $actNode = XML::LibXML::Element->new('actor');
                            $actNode->appendTextNode($actor);
                            $credits->appendChild($actNode);
                        }
                    } else {
                        $programme->removeChild($node);
                    }
                } elsif ($node->nodeName eq 'category') {
                    # FIXME where does the empty category element come from?
                    if (!$node->hasChildNodes()) {
                        $programme->removeChild($node);
                    }
                }
            }
            
            $writer->raw($programme->toString . "\n");
        }
        
    }
}

sub process_ruv_is ( $$$$$$ ){

    my ($writer, $fromdate, $num_days, $tv2chan, $timeoffset, $ch_xmltv_id) = @_;
    
    my $xsl_transform = <<"EOF";
        <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:data="urn:some.urn" exclude-result-prefixes="data">
        <xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes" />
        
        
        <data:category>
          <entry key="1">children</entry>
          <entry key="2">series</entry>
          <entry key="3">news</entry>
          <entry key="4">educational</entry>
          <entry key="5">sports</entry>
          <entry key="6">misc</entry>
          <entry key="7">movie</entry>
          <entry key="8">culture</entry>
          <entry key="9">music</entry>
        </data:category>
        
        <xsl:template match="/">
            <!-- XML needs a toplevel node, so we wrap the programmes in a channel_wrapper element.  The code will then remove it -->
            <channel_wrapper>
            <xsl:apply-templates/>
            </channel_wrapper>
        </xsl:template>
        
        <xsl:template match="event">
            <programme channel="$ch_xmltv_id" start="">
                <xsl:attribute name="start">
                    <xsl:value-of select='translate(\@start-time,"- :","")'/>
                </xsl:attribute>
                <title>
                    <xsl:apply-templates select="title"/>
                </title>
                <sub-title>
                    <xsl:apply-templates select="original-title"/>
                </sub-title>
        
                <desc>
                    <xsl:apply-templates select="description"/>
                </desc>
                <xsl:apply-templates select="credits" />
                <xsl:apply-templates select="category"/>
                <xsl:apply-templates select="episode"/>
                <xsl:apply-templates select="rerun"/>
            </programme>
        </xsl:template>

        <xsl:template match="credits[actor or director]">
            <xsl:copy-of select="." />
        </xsl:template>

        <!-- Two matches for <category>. With funky lookup as explained at http://www.ibm.com/developerworks/library/x-xsltip.html#h2 -->
        <xsl:template match="category[\@value &gt;= 1 and \@value &lt;= 9]">
            <category>
                <xsl:variable name="category_value"><xsl:value-of select="\@value" /></xsl:variable>
                <xsl:value-of select="document('')/*/data:category/entry[\@key = \$category_value]"/>
             </category>
        </xsl:template>
        <xsl:template match="category">
            &lt;!-- category is no good: <xsl:value-of select="\@value" /> --&gt;
        </xsl:template>
        
        <!-- Two matches for <episode> One to cut out "1 of 1", and one to change to "x:y" format -->
        <xsl:template match="episode[\@number = 1 and \@number-of-episodes = 1]">
        </xsl:template>
        <xsl:template match="episode">
            <episode-num system="onscreen"><xsl:value-of select="\@number"/>:<xsl:value-of select="\@number-of-episodes"/>
            </episode-num>
        </xsl:template>
        
        <!-- Two matches for <rerun>.  One turns 'yes' into <previously-shown>, the other cuts out the 'no's -->
        <xsl:template match="rerun[. = 'yes']">
            <previously-shown/>
        </xsl:template>
        <xsl:template match="rerun">
        </xsl:template>
        
        </xsl:stylesheet>
EOF

    # Get the XML.  Note that due to some edge cases, we must get data for the day before
    # and after the ones we're looking for and let process_xml_cannel remove most of the 
    # data.  If we don't, tv_validate_grabber will fail
    my $dayBefore = UnixDate(DateCalc($fromdate, "- 1 days"), '%Y-%m-%d');
    my $dayAfter = UnixDate(DateCalc($fromdate, "+ " . ($num_days + 1) . " days"), '%Y-%m-%d');
    my $url = "http://muninn.ruv.is/files/xml/sjonvarpid/$dayBefore/$dayAfter/";
    my  $xml = get_nice( $url ); die( "Failed to fetch $url" ) unless defined( $xml );
    
    process_xml_channel($writer, $fromdate, $num_days, $timeoffset, $xsl_transform, $xml);
}

sub process_skjarinn_is ( $$$$$$ ){

    my ($writer, $fromdate, $num_days, $tv2chan, $timeoffset, $ch_xmltv_id) = @_;
    
    # NOTE: For Skjar 1, we ignore $fromdate and $num_days and always load the next five days.
    
    my $xsl_transform = <<"EOF";
        <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
        <xsl:output method="xml" version="1.0" encoding="iso-8859-1" indent="yes"/>

        <xsl:template match="/">
            <!-- XML needs a toplevel node, so we wrap the programmes in a channel_wrapper element.  The code will then remove it -->
            <channel_wrapper>
            <xsl:apply-templates/>
            </channel_wrapper>
        </xsl:template>
        
        <xsl:template match="event">
            <programme channel="$ch_xmltv_id" start="">
                <xsl:attribute name="start">
                    <xsl:value-of select='translate(\@start-time,"- :","")'/>
                </xsl:attribute>
                <title>
                    <xsl:apply-templates select="title"/>
                </title>
                <desc>
                    <xsl:apply-templates select="description"/>
                </desc>
                <credits/>
            </programme>
        </xsl:template>
        
        </xsl:stylesheet>
EOF
    my $url = "http://skjareinn.is/einn/dagskrarupplysingar/?channel_id=7&weeks=2&output_format=xml";

    my  $xml = get_nice( $url ); die( "Failed to fetch $url" ) unless defined( $xml );
    
    process_xml_channel($writer, $fromdate, $num_days, $timeoffset,  $xsl_transform, $xml);
}

sub process_stod2_and_friends ( $$$$$$ ){

    my ($writer, $fromdate, $num_days, $tv2chan, $timeoffset, $ch_xmltv_id) = @_;
    
    # NOTE: For Stod 2 et al, we ignore $fromdate and $num_days and always load the next week.
    
    my $xsl_transform = <<"EOF";
        <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
        <xsl:output method="xml" version="1.0" encoding="iso-8859-1" indent="yes"/>

        <xsl:template match="/schedule">
            <!-- XML needs a toplevel node, so we wrap the programmes in a channel_wrapper element.  The code will then remove it -->
            <channel_wrapper>
            <xsl:apply-templates select="event[not(reference_number/\@value=following::event/reference_number/\@value)]" />
            </channel_wrapper>
        </xsl:template>
        
        <xsl:template match="event">
            <programme channel="$tv2chan.sjonvarp.is" start="">
                <xsl:attribute name="start">
                    <xsl:value-of select='translate(\@starttime,"- :","")'/>
                </xsl:attribute>
                <title>
                    <xsl:apply-templates select="title"/>
                </title>
                <sub-title>
                    <xsl:apply-templates select="org_title"/>
                </sub-title>
                <desc>
                    <xsl:apply-templates select="description"/>
                </desc>
                <credits/>
                <xsl:apply-templates select="episode"/>
            </programme>
        </xsl:template>

        <xsl:template match="series">
            <episode-num system="onscreen"><xsl:value-of select="\@episode"/>:<xsl:value-of select="\@series"/>
            </episode-num>
        </xsl:template>
        
        </xsl:stylesheet>
EOF
    
    my $url = $stod2AndFriends{basechid($tv2chan)};

    my  $xml = get_nice( $url ); die( "Failed to fetch $url" ) unless defined( $xml );
    
    process_xml_channel($writer, $fromdate, $num_days, $timeoffset,  $xsl_transform, $xml);
}

# get channel listing
sub get_channels {
    # I'm too lazy to figure out how to append plus channels programatically
    return  (
    "RUV" => "Ríkissjónvarpið",
    "S1" => "Skjár 1",
    "ST2" => "Stöð 2",
    "ST2SPORT" => "Stöð 2 Sport",
    "ST2SPORT2" => "Stöð 2 Sport 2",
    "ST2EXTRA" => "Stöð 2 Extra",
    "ST2BIO" => "Stöð 2 bíó",
    "plus.RUV" => "Ríkissjónvarpið+",
    "plus.S1" => "Skjár 1+",
    "plus.ST2" => "Stöð 2+",
    "plus.ST2SPORT" => "Stöð 2 Sport+",
    "plus.ST2SPORT2" => "Stöð 2 Sport 2+",
    "plus.ST2EXTRA" => "Stöð 2 Extra+",
    "plus.ST2BIO" => "Stöð 2 bíó+",
    );
}

# Icon URL for a given channel.
sub get_icon {
    my ($ch_did) = @_;
    $ch_did = basechid($ch_did);

    my %logos = (
        "RUV" => "ruv",
        "S1" => "s1",
        "ST2" => "stod2",
        "ST2SPORT" => "2sport",
        "ST2SPORT2" => "2sport2",
        "ST2EXTRA" => "2extra",
        "ST2BIO" => "2bio",
    );

    if (defined($logos{$ch_did})) {
        return "http://www.sjonvarp.is/images/logos/".$logos{$ch_did}.".gif";
    }
    return "";
}