#!/usr/bin/perl
# A simple EPG to HTML converter
#
# Converts the EPG data written by 'vdr' into the file /video/epg.data
# into a simple HTML programme listing, consisting of one file per channel
# plus an 'index.htm' file. All output files are written into the current
# directory.
#
# Usage: epg2html < /video/epg.data
#
# See the main source file 'vdr.c' for copyright information and
# how to reach the author.
#
# $Id: epg2html 2.2 2013/03/04 12:13:11 kls Exp $
@Index = ();
($Charset = $ENV{LANG}) =~ s/^[^.]*\.?(.*)/$1/;
$Charset = "utf-8" unless $Charset || $ENV{LANG} == 'C';
sub GetDay
{
  return substr(localtime(shift), 0, 10);
}
sub GetTime
{
  return substr(localtime(shift), 11, 5);
}
sub Tags
{
  my $s = shift;
  $s =~ s/\&/&/g;
  $s =~ s/</g;
  $s =~ s/>/>/g;
  return $s;
}
while (<>) {
      chomp;
      if (/^C ([^ ]+) *(.*)/) {
         my $Channel = $2;
         (my $Page = $Channel) =~ y/\/ /-_/;
         $Page .= ".htm";
         $Channel = Tags($Channel);
         push(@Index, qq{$Channel
\n});
         my %Events = ();
         while (<>) {
               if (/^E (.*?) (.*?) ([^ ]*)/) {
                  (my $Time, $Duration) = ($2, $3);
                  my $Title = "", $Subtitle = "", $Description = "", $Vps = 0;
                  while (<>) {
                        if    (/^T (.*)/) { $Title       = Tags($1); }
                        elsif (/^S (.*)/) { $Subtitle    = Tags($1); }
                        elsif (/^D (.*)/) { $Description = Tags($1); $Description =~ s/\|/
/g; }
                        elsif (/^V (.*)/) { $Vps         = $1; }
                        elsif (/^e/) {
                           $Events{$Time} = [($Duration, $Title, $Subtitle, $Description, $Vps)];
                           last;
                           }
                        }
                  }
               elsif (/^c/) {
                  my @Schedule = ();
                  my $Day = "";
                  for $t (sort keys %Events) {
                      (my $Duration, $Title, $Subtitle, $Description, $Vps) = @{$Events{$t}};
                      my $d = GetDay($t);
                      if ($d ne $Day) {
                         push(@Schedule, "\n") if ($Day && @Schedule);
                         push(@Schedule, "
| " . GetTime($t) . " | $Entry |