#!/usr/bin/perl -w

binmode(STDOUT, ':utf8');
use XML::LibXML::Reader;

open(my $fp, '<', './channel_ids') or die('No channel_ids');
my %channels;
while (<$fp>) {
    chomp;
    if ($_ !~ /^#/) {
        @line = split(';');
        $channels{$line[0]} = $line[1];
    }
}
close($fp);

my $xml = XML::LibXML::Reader->new(
    location => './channel_y.xml',
    encoding => 'UTF-8'
) or die('No channel_y.xml');

while ($xml->read()) {
    if ($xml->nodeType() == XML_READER_TYPE_ELEMENT &&
        $xml->name() eq 'data') {
        my $data = $xml->copyCurrentNode(1);
        my $id = $data->findvalue('ch4');
        my $name = $data->findvalue('ch0');
        my $dvb = $data->findvalue('ch11');
        $name .= " ($dvb)" if $dvb && $dvb ne $name;
        printf("%d;%s;%s\n",
               $id,
               $channels{$id} ? $channels{$id} : 'XMLTVID',
               $name
        );
    }
}
