#!/usr/bin/perl -w
use strict;
use XML::RSS::Parser;
use vars qw( $PROG );
( $PROG = $0 ) =~ s/^.*[\/\\]//;    # Truncate calling path from the prog name
my $AUTH    = 'Joshua D. Abraham';  # author
my $EMAIL   = 'jabra@spl0it.org';   # email
my $VERSION = '1.00';               # version
my %options;                        # getopt option hash
my $p    = XML::RSS::Parser->new;
my $feed = $p->parse_file('http://radio538.nl/538/xml/rss/dancedepartment.jsp');
use Getopt::Long;

#
# help:
# display help information
#
sub help {
    print "Usage: $PROG [Input Option] [Option] 
    -a  --all               Parse all items
    -r  --recent [num]      Parse recent [num] shows
    -f  --first [num]       Parse first [num] shows

    -u  --url               Parse file and extract links
        --author            Print the author
    -t  --title             Print the title
    
    -v  --version           Display version
    -h  --help              Display this information
Send Comments to $AUTH ( $EMAIL )\n";
    exit;
}

#
# print_version:
# displays version
#
sub print_version {
    print "$PROG version $VERSION by $AUTH ( $EMAIL )\n";
    exit;
}
GetOptions(
    \%options,
    'url|u', 'all|a', 'author', 'title|t', 'recent|r=s', 'first|f=s', 'date|d',
    'item|i=s',
    'help|h'    => sub { help(); },
    'version|v' => sub { print_version(); },
) or exit 1;

my @feed;
if ( $options{all} ) {
    @feed = $feed->query('//item');
}
elsif ( $options{item} ) {
    my $num = $options{item};
    @feed = $feed->query( '//item/[@title=~/Nr. ' . $num . '/]' );
}
elsif ( $options{recent} ) {
    my @new_feed = reverse( $feed->query('//item') );
    foreach (@new_feed) {
        unless ( scalar(@feed) == $options{recent} ) {
            push( @feed, pop(@new_feed) );
        }
    }
}
elsif ( $options{first} ) {
    my @new_feed = $feed->query('//item');
    foreach (@new_feed) {
        unless ( scalar(@feed) == $options{first} ) {
            push( @feed, pop(@new_feed) );
        }
    }
}
else {
    help();
}

foreach my $i (@feed) {
    if ( $options{title} ) {
        print $i->query('title')->text_content . "\n";
    }
    if ( $options{url} ) {
        print $i->query('enclosure')->attributes->{'{}url'} . "\n";
    }
    if ( $options{date} ) {
        print $i->query('pubDate')->text_content . "\n";
    }

}
