#!/usr/bin/perl -w

eval 'exec /usr/bin/perl -w -S $0 ${1+"$@"}'
    if 0; # not running under some shell

=pod

=head1 NAME

tv_to_text - Convert XMLTV listings to text.

=head1 SYNOPSIS

tv_to_text [--help] [--output FILE] [FILE...]

=head1 DESCRIPTION

Read XMLTV data and output a summary of listings.  The programme titles,
subtitles, times and channels are shown.

B<--output FILE> write to FILE rather than standard output

=head1 SEE ALSO

L<xmltv(5)>.

=head1 AUTHOR

Ed Avis, ed@membled.com

=cut

use strict;
use XMLTV::Version '$Id: tv_to_text,v 1.4 2003/06/29 15:53:51 epaepa Exp $ ';
use IO::File;
use Date::Manip; Date_Init('TZ=UTC');
use POSIX 'tmpnam';
use Getopt::Long;

# 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();
    }
}

use XMLTV qw(best_name);
use XMLTV::Summarize qw(summarize);
use XMLTV::Usage <<END
$0: convert listings to plain text
usage: $0 [--help] [--output FILE] [FILE...]
END
;

my ($opt_help, $opt_output);
GetOptions('help' => \$opt_help, 'output=s' => \$opt_output) or usage(0);
usage(1) if $opt_help;
@ARGV = ('-') if not @ARGV;
if (defined $opt_output) {
    open(STDOUT, ">$opt_output")
      or die "cannot write to $opt_output: $!";
}

# FIXME maybe memoize some stuff here

my ($encoding, $credits, $ch, $progs) = @{XMLTV::parsefiles(@ARGV)};
my $wrote_prog = 0;
foreach (summarize($ch, $progs)) {
    if (not ref) {
	print "\n" if $wrote_prog;
	print "$_\n\n";
	next;
    }
    my ($start, $stop, $title, $sub_title, $channel) = @$_;
    $stop = '' if not defined $stop;
    $title .= " // $sub_title" if defined $sub_title;
    print "$start--$stop\t$title\t$channel\n";
    $wrote_prog = 1;
}

# Acknowledgements
my $g = $credits->{'generator-info-name'};
$g =~ s!/(\d)! $1! if defined $g;
my $s = $credits->{'source-info-name'};
if (not defined $g and not defined $s) {
    # No acknowledgement since unknown source.
}
elsif (not defined $g and defined $s) {
    print "\nGenerated from $s.\n";
}
elsif (defined $g and not defined $s) {
    print "\nGenerated by $g.\n";
}
elsif (defined $g and defined $s) {
    print "\nGenerated from $s by $g.\n";
}
else { die }
