#!/usr/bin/perl

=pod

=head1 NAME

tv_count - Count (and print) the number of channels and programmes
in an XMLTV file.

=head1 SYNOPSIS

tv_count -i FILE

=head1 DESCRIPTION

Read XMLTV listings and print a count of the number of channels and
number of programmes in the file.

=head1 EXAMPLE

To print counts of all channels and programmes in the file called
F<listings.xml>:

  tv_count -i listings.xml

=head1 SEE ALSO

L<XMLTV(3)>

=head1 AUTHOR

Copyright Geoff Westcott, February 2013.

This code is distributed under the GNU General Public License v2 (GPLv2) .

=cut

use warnings;
use strict;

use XML::TreePP;
use Date::Parse;
use POSIX qw(strftime);

use Getopt::Std;
$Getopt::Std::STANDARD_HELP_VERSION = 1;

use Data::Dumper;

# Process command line arguments
my %opts = ();
getopts("dDqi:hv", \%opts);
my $input_file     = ($opts{'i'}) ? $opts{'i'} : "";
my $debug          = ($opts{'d'}) ? $opts{'d'} : "";
my $debugmore      = ($opts{'D'}) ? $opts{'D'} : "";
my $quiet_mode     = ($opts{'q'}) ? $opts{'q'} : "";

if ($opts{'h'}) {
    VERSION_MESSAGE();
    HELP_MESSAGE();
    exit;
}
if ($opts{'v'}) {
    VERSION_MESSAGE();
    exit;
}
if ( !%opts || ! defined $opts{'i'} || ! -r $opts{'i'} ) {
    HELP_MESSAGE();
    exit;
}
if ($debugmore) {
    $debug++;
}

# Parse the XMLTV file
my $tpp = XML::TreePP->new();
$tpp->set( force_array => [ 'channel', 'programme' ] );  # force array ref for some fields


my $xmltv = $tpp->parsefile( $input_file );
if ($debugmore) { print Dumper($xmltv); }


my $ccount = scalar @{ $xmltv->{'tv'}->{'channel'} };
my $ccount_plural = $ccount == 1 ? "" : "s";
my $pcount = scalar @{ $xmltv->{'tv'}->{'programme'} };
my $pcount_plural = $pcount == 1 ? "" : "s";
if (!$quiet_mode) { print "Count : $ccount channel$ccount_plural $pcount programme$pcount_plural \n"; }



###############################################################################
###############################################################################


sub VERSION_MESSAGE {
    use XMLTV;
    my $VERSION = $XMLTV::VERSION;

    print "XMLTV module version $XMLTV::VERSION\n";
    print "This program version $VERSION\n";
}

sub HELP_MESSAGE {
    # print usage message
    my $filename = (split(/\//,$0))[-1];
		print << "EOF";

Count (and print) the number of channels and programmes in an XMLTV file

Usage: $filename [-dDq] -i FILE

-i FILE  : input XMLTV file

-d       : print debugging messages
-D       : print even more debugging messages
-q       : quiet mode (no STDOUT messages)

-h, --help
         : print help message and exit
-v, --version
         : print version and exit

Example: $filename -i listings.xml

EOF
}
