#!/usr/bin/perl -w 
# Russian XMLTV grabber: JTV format
#
# Changelog: 
# 0.4 - fixed bug caused by not finding one of the pdt/ndx files in the downloaded data package
# 0.3 - additional timeshifting for individual channels, RAR support (if unrar command is available), Use unzip for unzipping, Allow to specify alternative data sources via command options 
# 0.2 - do not delete downloaded data if --cache option is used, support --preferredmethod 
# 0.1 - first running version for JTV

=pod

=head1 NAME

tv_grab_ru_jtv - Grab TV listings for Russian channels.

=head1 SYNOPSIS

tv_grab_ru_jtv 	
		[--quiet] 
		[--output FILE] 
		[--config-file FILE] 
		[--days N] 
		[--offset N] 
		[--cache FILE] 
		[--share DIR] 
		[--timezone ZONE]
		[--encoding CODEPAGE]
		[--src-url URL]
		[--src-timezone ZONE]

tv_grab_ru_jtv --configure 
		[--config-file FILE] 
		[--gui OPTION] 
		[--cache FILE] 
		[--share DIR]
		[--src-url URL]
		[--src-timezone ZONE]

tv_grab_ru_jtv --list-channels 
		[--cache FILE] 
		[--encoding CODEPAGE] 
		[--share DIR]
		[--src-url URL]
		[--src-timezone ZONE]

tv_grab_ru_jtv --capabilities

tv_grab_ru_jtv --preferredmethod

tv_grab_ru_jtv --description

tv_grab_ru_jtv --help

tv_grab_ru_jtv --version

=head1 DESCRIPTION

Output TV listings for Russian channels. It will download data in JTV format. 
If for any reason you cannot access the Internet download site, you can still 
use any JTV files locally either zipped or unzipped to disk. The best time to 
run this script is probably on Sunday evening or Monday morning.

First run B<tv_grab_ru_jtv --configure> to choose, which channels you want
to download. Then running B<tv_grab_ru_jtv> with no arguments will output
listings in XML format to standard output.

B<--configure> Prompt for which channels,
and write the configuration file.

B<--config-file FILE> Set the name of the configuration file, the
default is B<~/.xmltv/tv_grab_ru_jtv.conf>.  This is the file written by
B<--configure> and read when grabbing.

B<--gui OPTION> Use this option to enable a graphical interface to be used.
OPTION may be 'Tk', or left blank for the best available choice.
Additional allowed values of OPTION are 'Term' for normal terminal output
(default) and 'TermNoProgressBar' to disable the use of XMLTV::ProgressBar.

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

B<--days N> grab N days.  The default is 7. This has little meaning because 
the data seems to be refreshed once a week on Sundays and always covers 7 days. 
Any choice will either remove some information or have no effect.

B<--offset N> start N days in the future.  The default is to start
from today.

B<--quiet> suppress the progress messages normally written to standard
error.

B<--cache FILE> read data from a local file (or directory) instead of downloading.
Accepts path to zip archive, pair of NDX/PDT files or a directory with such files. 
If the specified file does not exist, a new portion of zipped data will be 
downloaded and saved to that path. 

B<--encoding CODEPAGE> output the XML using CODEPAGE. Default is Unicode UTF-8 unless
your locale is ru_RU. In Russian environment the system default encoding is used. 

B<--timezone TZ> Convert all programme times to specified timezone. If this option 
is absent, the program will use +0000 (UTC) timezone to write data. 
Time zones should be specified according to RFC 822:

    Universal:  GMT, UT
    Abbreviations :  EET, MSK, MSD, BT, ZP4, ZP5 etc. 
    Military :  A to Z (except J)
    Other    :  +HHMM or -HHMM
    ISO 8601 :  +HH:MM, +HH, -HH:MM, -HH

B<--share> Specify the directory where the channel_ids file is located.

B<--src-url> URL to download the source data. Use this option if you want to use a 
different source to download the JTV data package.

B<--src-timezone> assume that the input data provides time using the specified TZ.

B<--capabilities> Show which capabilities the grabber supports. For more
information, see L<http://membled.com/twiki/bin/view/Main/XmltvCapabilities>

B<--preferredmethod> Tell to the calling application that the grabber downloads
all data in one big chunk.

B<--description> Show short description of the grabber.

B<--version> Show the version of the grabber.

B<--help> print a help message and exit.

=head1 SEE ALSO

L<xmltv(5)>.

=head1 AUTHOR

Vyacheslav Dikonov, sdiconov@mail.ru

=head1 BUGS

=cut

######################################################################
# Initialisation

use strict;

use utf8;
use POSIX;
use Encode;
use Math::BigInt; # Ms style timestamp conversion
use Memoize; # 2x speedup for the parser
memoize('Date_ConvTZ');
memoize('Date_Cmp');

use XMLTV;
use XMLTV::Get_nice;
# Options
use Getopt::Long;
use XMLTV::Ask;
use XMLTV::Mode;
use XMLTV::Config_file;
# capabilities
use XMLTV::Version '$Id: tv_grab_ru_jtv,v 0.3 2008/08/24 09:20:00 Exp $ ';
use XMLTV::Capabilities qw/baseline manualconfig tkconfig preferredmethod share cache/;
use XMLTV::PreferredMethod 'allatonce';
use XMLTV::Description 'Russia, Belarus, Ukraine (JTV format)';
# get_channels
use XMLTV::ProgressBar;
use Date::Manip;
use XMLTV::Date;
use File::Spec::Functions;
# Unpack
use File::Path;
use File::Basename;
    
use XMLTV::Usage <<END
$0: get Russian Ukrainian and Belorussian television listings in XMLTV format

To configure: $0 --configure [--config-file FILE] [--cache FILE] [--gui OPTION] [--share DIR]
                [--src-url URL] [--src-timezone TZ]
To grab listings: $0 [--quiet] [--output FILE] [--config-file FILE] [--days N] [--offset N] 
                [--cache FILE] [--share DIR] [--timezone TZ] [--encoding CODEPAGE]
                [--src-url URL] [--src-timezone TZ]
To list channels: $0 --list-channels [--cache FILE] [--encoding CODEPAGE] [--share DIR]
                [--src-url URL] [--src-timezone TZ]
To show capabilities: $0 --capabilities
To show preferred method: $0 --preferredmethod
To show description: $0 --description
To show version: $0 --version

END
;
delete $ENV{BASH_ENV};
$ENV{PATH} = '/bin:/usr/bin';

######################################################################
# Data source configuration
my $url_icons = "http://www.free-x.de/teleweb/icons";
my $url_datafile = "http://tuner.beholder.ru/jtv.zip";
my $input_encoding = "windows-1251"; # Beholder stores show names in cp1251
my $input_timezone = "+0200"; # Eastern Europe, USSR 1 (Kiev, Kalinigrad)
# Some alternative URLs:
#my $url_datafile = "http://www.teleguide.info/download/new3/jtv.rar";
#my $url_datafile = "http://jtv-proxy.appspot.com/file.rar";
my $src_info;

######################################################################
# get options

my ($opt_days, $opt_offset, $opt_help, $opt_output, $opt_configure, $opt_config_file, $opt_gui,
    $opt_quiet, $opt_list_channels, $opt_local_path, $opt_local_dir, $opt_output_encoding, 
    $opt_output_timezone, $opt_share_dir);
$opt_days  = 7; # default
$opt_offset = 0; # default
$opt_quiet  = 0; # default
$opt_output_timezone = "+0000"; #default UTC
$opt_share_dir = "/usr/share/xmltv/tv_grab_ru"; #default
GetOptions('days=i'        => \$opt_days,
	   'offset=i'      => \$opt_offset,
	   'help'          => \$opt_help,
	   'configure'     => \$opt_configure,
	   'config-file=s' => \$opt_config_file,
	   'cache=s'       => \$opt_local_path,
           'gui:s'         => \$opt_gui,
	   'output=s'      => \$opt_output,
	   'quiet'         => \$opt_quiet,
	   'list-channels' => \$opt_list_channels,
	   'encoding=s'    => \$opt_output_encoding,
	   'timezone=s'    => \$opt_output_timezone,
	   'share=s'	   => \$opt_share_dir,
	   'src-url=s'	   => \$url_datafile,
	   'src-timezone=s'	   => \$input_timezone
	  )
  or usage(0);
die 'number of days must not be negative'
  if (defined $opt_days && $opt_days < 0);
usage(1) if $opt_help;

XMLTV::Ask::init($opt_gui);

my $mode = XMLTV::Mode::mode('grab', # default
			     $opt_configure => 'configure',
			     $opt_list_channels => 'list-channels',
			    );


######################################################################
# Set global variables
my @extlist = ('.ndx', '.pdt'); # Extensions of the JTV files

# Source Information
$src_info = $url_datafile;
$src_info =~ s/[fhtp]+\:\/\///;
$src_info =~ s/\/.*$//;

# Grabber configuration
my $config_file = XMLTV::Config_file::filename($opt_config_file, 'tv_grab_ru_jtv', $opt_quiet); # File that stores which channels to download.
my $id_file = "channel_ids"; # file of id aliases and names
my $shift_file = "timeshift"; # list of compensatory timeshifts for individual channels
$XMLTV::Get_nice::Delay = 0; # No need to be nice.
Date_Init("DateFormat=non-US", "Internal=1");

my %writer_args; # XMLTV::Writer arguments (XML encoding and output)
my %pr_data; # ID - @list of programmes (start, name)
my %ch_data; # ID - Name hashlist of channels
my @id_alias; # ID aliases and names for channel matching
my @timeshift; # timeshifts for individual channels (optional)
my $new_ch_counter = 0; #count new channels for which no id can be found

# Detect locale and set output encoding if possible (UNIX specific part)
my $syslocale = setlocale(LC_CTYPE);
my $sysencoding = "ASCII"; # default system encoding
my $syslanguage;
my $syscountry;

if ( $syslocale =~ m/\./ ) { 
    ($sysencoding = $syslocale) =~ s/.*\.//;
    $syslocale =~ s/\..*//;
};

if ( $syslocale =~ m/_/ ) { 
    ($syslanguage = $syslocale) =~ s/_.*//;
    ($syscountry = $syslocale) =~ s/.*_//;
} else { 
    $syslanguage = $syslocale 
};

if ($sysencoding =~ m/(1251|koi8|koi-8|iso8859-5|866|UTF-8)/i ) {
    if (not defined $opt_output_encoding) {$opt_output_encoding = $sysencoding};   # Use sysenc if output enc option is not given 
    if ($opt_output_encoding eq "CP1251") {$opt_output_encoding = "windows-1251"}; # Fix for perl frontends  
} else { $opt_output_encoding = "UTF-8" };

# Define XMLTV::Writer parameters
if ($mode eq 'list-channels' or $mode eq 'grab') { # only writing modes need this  
    $writer_args{encoding} = $opt_output_encoding; # sets the encoding field in the XML header
    if (defined $opt_output) { # if the --output option is present
	$writer_args{OUTPUT} = new IO::File(">$opt_output"); # create the output file
	die "cannot write to $opt_output: $!" if not defined $writer_args{OUTPUT};
    };
};

######################################################################
# Configure

if ($mode eq 'configure') {

    my @names;

    XMLTV::Config_file::check_no_overwrite($config_file);
    
    get_data();
    # unless run in grab mode this routine only retrieves channel names (hacky speedup in parsetxt)
    
    # write configuration
    if ($mode eq 'configure') {
	open(CONF, "> $config_file") or	die "cannot write to $config_file: $!"; 

	# Ask about each channel.
	my @chs = sort keys %ch_data;
	@names = map {encodeoutstr("$ch_data{$_}")} @chs;
	my @want = ask_many_boolean(1, @names);
	foreach (@chs) {
	    my $w = shift @want;
	    warn("cannot read input, stopping channel questions"), last
	      if not defined $w;
	    print CONF '#' if not $w;
	    my $name = shift @names;
	    print CONF encode($opt_output_encoding, "channel $_ $name\n");
	};

	close CONF or warn "cannot close $config_file: $!";
        say("Finished configuration.");

        exit();
    }
}

######################################################################
# List channels
elsif ($mode eq 'list-channels') {

    get_data();
    # unless run in grab mode this routine only retrieves channel names (hacky speedup in parsetxt)

    my $writer = new XMLTV::Writer(%writer_args);
    $writer->start({ 	'source-info-url' => $src_info,
			'source-data-url' => $url_datafile,
			'generator-info-name' => "XMLTV",
			'generator-info-url' => "http://membled.com/work/apps/xmltv/" });

    foreach (keys(%ch_data)) {
        $writer->write_channel({id => $_, 'display-name' => [ [ encode($opt_output_encoding, $ch_data{$_}), 'ru' ] ]});
    };
    $writer->end();

    exit();
}

######################################################################
# Grab

elsif ($mode eq 'grab') {

my %rawdata;
my $bar;

    my @config_lines = XMLTV::Config_file::read_lines($config_file);
    my (%channels, %prog);
    my ($ch_id, $ch_name, $pr_start);
    
    # Read configuration
    my $line_num = 1;
    foreach (@config_lines) {
        ++ $line_num;
        next if not defined;
        if (/^channel:?\s+(\S+)\s+([^\#]+)/) {
	    $ch_id = $1;
	    $ch_name = $2;
	    $ch_name =~ s/\s*$//;
	    $channels{$ch_id} = $ch_name;
	}
	else {
	    warn "$config_file:$line_num: bad line\n";
        }
    };

    die "No channels specified, run me with --configure\n" if not keys %channels;

    # Set time limits
    my $now = DateCalc(parse_date('now'), "$opt_offset days");
    my $timefiltstart = $now;
    if ($opt_offset) { $timefiltstart = DateCalc($now,"+ $opt_offset days") };
    my $timefiltend = DateCalc($timefiltstart,"+ $opt_days days");

    # Process and output
    get_data(\%channels); 
    # we give reference to the selected channels list for speedup

    unless ($opt_quiet) { $bar = new XMLTV::ProgressBar("Writing data", 101) };
    my $count = 0; # count cycles

    my $writer = new XMLTV::Writer(%writer_args); # Header and channels
    $writer->start({ 	'source-info-url' => $src_info,
			'source-data-url' => $url_datafile,
			'generator-info-name' => "XMLTV",
			'generator-info-url' => "http://membled.com/work/apps/xmltv/" });

    foreach $ch_id (keys %channels ) { # Write channels
	$count ++; # count cycles for bar update	    
	if ( exists($ch_data{$ch_id}) ) { # Only wanted channels
            $writer->write_channel({'id' => $ch_id, 
				    'display-name' => [ [ encode($opt_output_encoding, $ch_data{$ch_id}), 'ru' ] ], 
				    'icon' => [ { 'src' => $url_icons."/".$ch_id.".png" } ] });
	};
	unless ($opt_quiet) { update $bar (100/(((keys %channels) * 2)/$count)) };
    };

    foreach $ch_id (sort (keys %channels)) { # Write progs
	$count ++; # count cycles for bar update	    
	if ( exists($ch_data{$ch_id}) ) { # Only wanted channels 
	    foreach $pr_start (sort (keys %{$pr_data{$ch_id}}) ) {

		my $futureflag = Date_Cmp($pr_start, $timefiltend);
		my $pastflag; # Include currently broadcasted programme, if its stop time is known
		if ( defined ${${$pr_data{$ch_id}}{$pr_start}}{'stop'} ) {
		    $pastflag = Date_Cmp(${${$pr_data{$ch_id}}{$pr_start}}{'stop'}, $timefiltstart);
		} else {$pastflag = Date_Cmp($pr_start, $timefiltstart) };
	    
		if ( $pastflag >= 0 and $futureflag <= 0 ) { # Only falling into the specified timegap

		    $prog{'channel'} = $ch_id;
		    $prog{'start'} = $pr_start;
		    if ( defined ${${$pr_data{$ch_id}}{$pr_start}}{'stop'} ) {
			$prog{'stop'} = ${${$pr_data{$ch_id}}{$pr_start}}{'stop'};
		    };	
		    $prog{'title'} = [ [ encode($opt_output_encoding, ${${$pr_data{$ch_id}}{$pr_start}}{'title'} ), 'ru' ] ];
		    if ( defined ${${$pr_data{$ch_id}}{$pr_start}}{'desc'} ) {
			$prog{'desc'} = [ [ encode($opt_output_encoding, ${${$pr_data{$ch_id}}{$pr_start}}{'desc'} ), 'ru' ] ];
		    };
		    if ( defined ${${$pr_data{$ch_id}}{$pr_start}}{'category'} ) {
			$prog{'category'} = [ [ encode($opt_output_encoding, ${${$pr_data{$ch_id}}{$pr_start}}{'category'} ), 'ru' ] ];
		    };
		    $writer->write_programme(\%prog);
		    undef %prog;
		};
	    };
	};
	unless ($opt_quiet) { update $bar (100/(((keys %channels) * 2)/$count)) };
    };

    $writer->end();
    unless ($opt_quiet) {
	update $bar (101);
	$bar->finish()
    };

exit();
}
else { die };

# END

######################################################
# Service routines

sub cleanupstr ($) { # Remove leading and trailing spaces
    my $str=$_[0];

    if (not defined $str) {$str = ""}  else {
	$str =~ s/^\s+//;  
	$str =~ s/\s+$//;  

	# Fix some bad symbols that do not recode well
	s/—/-/g; # m-dash
	s/…/.../g; # ellipsis
	s/‘/\"/g; # Left quote
	s/’/\"/g; # Right quote
    };

    return $str; 
};

sub cookstr($) { # helps to distinguish strings that are really different from alternative writings
    my $str=$_[0];

    $str =~ s/\s//g;
    $str =~ s/\"//g;
    $str =~ s/\'//g;
    $str =~ s/\-//g;
    $str =~ s/\_//g;
    $str =~ s/\(//g;
    $str =~ s/\)//g;
    $str =~ s/\.//g;
    $str =~ s/\,//g;
    $str =~ s/\?//g;
    $str =~ s/\!//g;
    $str =~ s/\&//g;
    $str =~ s/\$//g;
    $str = lc($str);
    
    return $str;
};

sub encodeoutstr($) { # encode channel names to system encoding in console mode or use utf8 for GUI 
    my $str=$_[0];

	if (defined $opt_gui or not defined $sysencoding) { 
	    return $str;
	} else {
	    return encode($sysencoding, $str);
	};
};


sub setcategory ($) { #Try to guess type of the programme

    my %cat = ( '(Х\/ф|Худ\.фильм|Художественный фильм|Комедия|Мелодрама|Триллер|Боевик|Ужасов|Ужастик|Кинофильм|Телефильм)' => 'Художественный фильм',
    	'(Т\/с|Телесериал|^Сериал| Сериал)' => 'Телесериал',
    	'(М\/с|Мультсериал|Мультипликационный сериал)' => 'Мультипликационный сериал',
    	'(М\/ф|Мультфильм|Мультипликационный фильм)' => 'Мультфильм',
    	'(Д\/с|Док\.сериал|Документальный сериал)' => 'Документальный сериал',
    	'(Д\/ф|Док\.фильм|Документальный фильм|Кинофильм|Телефильм)' => 'Документальный фильм',
    	'(Фильм-спектакль|Спектакль)' => 'Спектакль',
    	'Концерт' => 'Концерт',
    	'Комедия' => 'Комедия',
    	'Мелодрама' => 'Мелодрама',
    	'Триллер' => 'Триллер',
    	'Боевик' => 'Боевик',
    	'(Ужасов|Ужастик)' => 'Фильм ужасов',
   	'(Новости|Вести|Время)' => 'Новости'
#   	'Шоу'
    );

    my $pr_name = $_[0];
    my $pr_cat;
    
    foreach (sort (keys %cat)) {
	if ( $pr_name =~ m/$_/i ) {
	    if ( defined $pr_cat) {$pr_cat .= " / ".$cat{$_};}
	    else {$pr_cat = $cat{$_};};		
	};
    };    
    return $pr_cat;
};

# Process contents of JTV NDX/PDT files 
# results are stored in the global data structure
sub parsejtvdata ($) { # JTV data structure 
    my ($data) = @_ ;
    my ($recsnum, $offset); # NDX vars
    my ($pdtoffset, $len); # PDT vars
    my ($i, $time, $pr_start, $pr_title, %ch_data, @times);

    # Parse JTV data
    # NDX   !!! unpacking can be architecture dependent. Tested on a 32-bit Intel machine
    $recsnum = unpack("x0 S1", ${$data}{'ndx'}); # Read number of records from NDX (first 2 bytes)
    $offset = 2; # Start reading

    for ($i=0; $i<$recsnum; $i++) { # Read records

	# Get the time value
	$offset = $offset + 2; # Skip 2 unused bytes before each record
	$time = Math::BigInt->new("0b".unpack("B*", reverse(unpack("x$offset a8", ${$data}{'ndx'})))); # Time is stored as a 64-bit integer in binary format. This byte sequence has to be reversed.
	$offset = $offset + 8;
	
	# Recalc the time to Unix time
	$time->bdiv('10000000'); # To seconds
	$time->bsub('11644473600'); # - ((369 * 365 + 89) * 86400) : To UNIX Epoch

        # Get the offset of the corresponding show name in PDT
	$pdtoffset = unpack("x$offset S1", ${$data}{'ndx'});
	$offset = $offset + 2;
	
	#PDT - Get shownames from PDT file
	$len = unpack("x$pdtoffset S1", ${$data}{'pdt'});
	$pr_title = decode($input_encoding, unpack("x$pdtoffset x2 a$len", ${$data}{'pdt'}));

	# Convert time. Note: The time in the data is EET(+2) and should be converted later.
	$pr_start = ParseDateString("epoch ".$time->bstr());
	if ($opt_output_timezone) { # Set correct timezone
	    $pr_start = Date_ConvTZ($pr_start, $input_timezone, $opt_output_timezone);
	}; 
	# Add a timeshift if provided in the timeshift file
	if (${$data}{'shift'}) {
	    $pr_start = DateCalc($pr_start, "${$data}{'shift'} minutes");
	};
	
	# Append timezone
	$pr_start .= " ".$opt_output_timezone;

	# Put a programme into the global listing
	# Here we process exactly one programme at a time 
	${${$pr_data{${$data}{'id'}}}{$pr_start}}{'title'} = $pr_title;
	${${$pr_data{${$data}{'id'}}}{$pr_start}}{'category'} = setcategory($pr_title);
    };

    @times = (sort (keys %{$pr_data{${$data}{'id'}}} ));

    for ($i=0; $i <= $#times; $i++)  {  # Set fake stop times.
	if ($i <= ($#times - 1)) { #Assume that the stop time of a prog is the start time of the next one 
	    ${${$pr_data{${$data}{'id'}}}{$times[$i]}}{'stop'} = $times[$i+1];
	}; # Last known programme of the day has no stop time
    };

};

sub readtxt ($$$) { # Read any text file into an array (ignore lines starting with "#") Used for config files.
    my ($file, $txt, $enc) = @_;
    if (open (FILE, "< $file")) { 
        while (<FILE>) { 
	    chomp;
	    s/\x0d//g; # Windows linefeed
	    $_ = decode($enc, $_);
	    push (@{$txt}, $_);
	};
	close (FILE);
    } else { say "unable to read ".$file };
};

sub readjtvdata ($$) { # Read a pair of JTV files into memory
    my ($file, $data) = @_;
    my ($fname, $fpath, $fext, $buf);
    
    ($fname, $fpath, $fext) = fileparse($file, @extlist);
    $file = catfile($fpath, $fname); # removes extension

    # Channel names and IDs
    ${$data}{'name'} = decode($sysencoding, $fname); # Channel name is the file name
    getchannelid(\${$data}{'name'}, \${$data}{'id'}); # Set channel ID
    $ch_data{${$data}{'id'}} = ${$data}{'name'}; # Build list of channel names
    gettimeshift(${$data}{'id'}, \${$data}{'shift'}); # Set compensatory timeshift for the current channel
    
    # Read NDX
    if (open (NDXFILE, "< $file.ndx")) { # FIXME!!! Possible extension case problems
	binmode (NDXFILE);
	while (read (NDXFILE, $buf, 8 * 1024)) { 
	    ${$data}{'ndx'} .= $buf;
	    undef $buf;
	};
	close (NDXFILE);
    } else {
	say "unable to read ".$file.".ndx"; 
	return 0; 
    };

    # Read PDT
    if (open (PDTFILE, "< $file.pdt")) {
	binmode (PDTFILE);
	while (read (PDTFILE, $buf, 8 * 1024)) {
	    ${$data}{'pdt'} .= $buf;
	    undef $buf;
	}; 
	close (PDTFILE);
    } else {
	say "unable to read ".$file.".pdt"; 
	return 0; 
    };
    return 1;
};

sub getchannelid ($$) { # receive a references to channel name and id vars and set them
    my ($ch_name, $ch_id)= @_; 
    my (@record, @names);
    my $name = cookstr(${$ch_name});
    
    foreach (@id_alias) { # parse list of ids and names
	if (m/./ and not m/^#/) { # skip comments and empty lines
    	    @record = split (/\:/, $_);
	    if (@record == 2) {
		@names = split (/\|/, $record[1]);
		foreach (@names) { 
		    if ( $name eq cookstr($_) ) { 
			${$ch_id} = cleanupstr($record[0]); 
			${$ch_name} = cleanupstr($names[0]); # Use first variant from the name list (to unify channel names from different grabs and sources) 
			last; 
		    };
		}; 
    	    } else { say "bad alias file line ".encodeoutstr($_) };
	};
    };
    if (not defined ${$ch_id}) { # No ID found in the list - create a dummy one and count new channels
	#if ( $mode eq 'grab' ) { say "unknown channel ".encodeoutstr(${$ch_name}).". using dummy id new_channel_".$new_ch_counter."." };
	${$ch_id} = "new_channel_".$new_ch_counter; 
	$new_ch_counter++;
    };
};

sub gettimeshift ($$) { # parse the list of timeshifts per channel 
    my ($ch_id, $ch_shift)= @_; 
    my (@record);
    
    foreach (@timeshift) { # parse list of timeshifts
	if (m/./ and not m/^#/) { # skip comments and empty lines
    	    @record = split (/\:/, $_);
	    if (@record == 2 and $record[1] =~ m/^[\+\-]\d+$/ ) {
		if (cleanupstr($record[0]) eq $ch_id ) {
		    ${$ch_shift} = cleanupstr($record[1]); 
		    last; 
		};
    	    };
	};
    };
    if (not defined ${$ch_shift}) { # No shift found in the list - use 0
	${$ch_shift} = ""; 
    };
};

# Unzip
sub unzipdata ($$) { # Use unzip to unpack a zip file to a temp dir and process that dir as local data. Second parameter is an optional list of requested channels (used in grab mode)
    my ($localpath, $channels) = @_; 
    my $tmpdir;

    $tmpdir = tmpnam();
    mkpath([$tmpdir]);
    system "unzip $localpath -d $tmpdir > /dev/null";
    if (-d $tmpdir) {
	processdir($tmpdir, $channels);
	rmtree([$tmpdir]);
    } else { say "Unable to unzip $localpath." };
};

sub unrardata ($$) { # Use unrar to unpack a rar file to a temp dir and process that dir as local data. Second parameter is an optional list of requested channels (used in grab mode)
    my ($localpath, $channels) = @_; 
    my $tmpdir;

    $tmpdir = tmpnam();
    mkpath([$tmpdir]);
    system "unrar e $localpath $tmpdir > /dev/null";
    if (-d $tmpdir) {
	processdir($tmpdir, $channels);
	rmtree([$tmpdir]);
    } else {say "Unable to unrar $localpath."};
};

sub processdir ($$) { # Read unpacked data from a specified directory
    my ($localpath, $channels) = @_; # Optional list of requested channels 
    my (@lst, %data); 
    my ($file, $path);
    my $bar;

    local (*ROOT);
    opendir ROOT, $localpath; # List directory
    @lst = readdir ROOT;
    closedir ROOT;


    unless ($opt_quiet) { $bar = new XMLTV::ProgressBar("Parsing data", 101) };
    my $count = 0; # count cycles

    foreach $file (@lst) # Create global rawdata structure from JTV files
    {
	$count++; # count cycles for bar update	    
	$path = catfile ($localpath, $file); # Make full path
	if (no_upwards($file) and -f $path) {
	    if ($file =~ m/\.ndx$/i) { # Only NDX files. Each NDX file must have a PDT.
		if ( readjtvdata($path, \%data) ) { # If it is possible to read both files
		
		    if ($mode eq 'grab') { # Only the grab mode requires full parsing.
			if ( defined $channels and exists( ${%{$channels}}{$data{'id'}} ) ) { # Speedup. No need to read unrequested channels.
			    parsejtvdata(\%data);  
			};
		    };
		    unless ($opt_quiet) { update $bar (100/(@lst/$count)) };
		};
		undef %data;
	    };
	}; 
    };
    unless ($opt_quiet) {
	update $bar (101);
	$bar->finish();
    };
    undef @lst; 
};

sub processfilepair ($$) { # Process a pair of JTV files
    my ($localpath, $channels) = @_; # Optional list of requested channels 
    my %data; 

    if ( readjtvdata($localpath, \%data) ) { # If it is possible to read both files

	if ($mode eq 'grab') { # Only the grab mode requires full parsing.
	    if ( defined $channels and exists( ${%{$channels}}{$data{'id'}} ) ) { # Speedup. No need to read unrequested channels.
		say "parsing data";
		parsejtvdata(\%data);  
	    };
	};
    };
    undef %data;
};

# Autodetect data type (zip/filepair/dir) and process it
sub processlocaldata ($$) {
    my ($localpath, $channels) = @_; # Optional list of requested channels 

	if ( -f $localpath and $localpath =~ m/zip$/i ) { 
	    unzipdata($localpath, $channels);
	} elsif ( -f $localpath and $localpath =~ m/rar$/i ) { 
	    unrardata($localpath, $channels);
	} elsif ( -f $localpath ) {
	    processfilepair($localpath, $channels);
	} elsif ( -d $localpath ) {
	    processdir($localpath, $channels);
	} else {
	    say "no data at the expected temporary path ".$localpath; 
	};
};

# Download / read
sub get_data { 
    
    my ($channels) = @_; # Optional list of requested channels 
    my $TMPFILE;
    my $newfile;
    my $ext; # type of the dowloaded file
    
    # Read list of channel names and IDs into memory
    if ( -f catfile($opt_share_dir, $id_file) ) { 
	readtxt(catfile($opt_share_dir, $id_file), \@id_alias, 'UTF-8'); 
	unless ($opt_quiet) {say "using metadata filename ".catfile($opt_share_dir, $id_file)}; 
    } elsif ( -f catfile(getcwd, $id_file) ) { 
	readtxt(catfile(getcwd, $id_file), \@id_alias, 'UTF-8');
	unless ($opt_quiet) {say "using metadata filename ".catfile(getcwd, $id_file)}; 
    } else { die "Unable to find channel ID metadata file ".catfile($opt_share_dir, $id_file).".\n"};

    # Read timeshift list into memory
    if ( -f catfile($opt_share_dir, $shift_file) ) { 
	readtxt(catfile($opt_share_dir, $shift_file), \@timeshift, 'UTF-8'); 
	unless ($opt_quiet) {say "using timeshift list ".catfile($opt_share_dir, $shift_file)}; 
    } elsif ( -f catfile(getcwd, $shift_file) ) { 
	readtxt(catfile(getcwd, $shift_file), \@timeshift, 'UTF-8');
	unless ($opt_quiet) {say "using timeshift list ".catfile(getcwd, $shift_file)}; 
    };

    if ( defined $opt_local_path and (-f $opt_local_path or -d $opt_local_path) ) { # Read already existing files
	processlocaldata($opt_local_path, $channels);
    } else { # Download
	my $data = get_nice($url_datafile);
	die "could not get datafile $url_datafile, aborting\n" if not defined $data;
	
	if ($url_datafile =~ m/rar$/) {$ext = ".rar"} # Preserve file extension
	elsif ($url_datafile =~ m/zip$/) {$ext = ".zip"}
	else {$ext = ""};

	if ( defined $opt_local_path ) { # Use supplied path for download if --cache option was used
	    $newfile = $opt_local_path;
	} else { # Temp file creation
	    do { $newfile = tmpnam()."$ext" } until $TMPFILE = IO::File->new($newfile, O_RDWR|O_CREAT|O_EXCL);
	};
		
	open (TMPFILE, "> $newfile") or die "unable to write temp source data file ".$newfile.", aborting.";
	binmode(TMPFILE);
	print TMPFILE $data;
	close(TMPFILE);
	undef $data;

	processlocaldata($newfile, $channels);
	
	unless ( defined $opt_local_path ) { # Delete the temp file only if no --cache option was supplied
	    if ( defined $newfile and -f $newfile ) {unlink($newfile) or say "could not delete temp file ".$newfile}
	};
    };
};
