#!/usr/bin/perl
use strict ;
use Pod::Usage ;
use Getopt::Long qw/:config no_ignore_case/ ;

++$! ;

use Linux::DVB::DVBT ;

	my ($help, $man, $DEBUG, $VERBOSE, $config, $clean, $check, $noprune) ;
	GetOptions('v|verbose=s' => \$VERBOSE,
			   'debug=s' => \$DEBUG,
			   'h|help' => \$help,
			   'man' => \$man,
			   'clean' => \$clean,
			   'cfg=s' => \$config,
			   'noprune' => \$noprune,
			   'check' => \$check,
			   ) or pod2usage(2) ;

	# force checking on
	$check = 1 ;

    pod2usage(1) if $help;
    pod2usage(-verbose => 2) if $man;
    
    if (@ARGV == 0)
    {
    	print "$0: No files given.\n" ;
    	pod2usage(-verbose => 2) ;
    }

$VERBOSE ||= 1 ;
	Linux::DVB::DVBT->debug($DEBUG) ;
	Linux::DVB::DVBT->dvb_debug($DEBUG) ;
	Linux::DVB::DVBT->verbose($VERBOSE) ;

	## Create dvb (use first found adapter). 
	## NOTE: With default object settings, the application will
	## die on *any* error, so there is no error checking in this script
	##
	my $dvb = Linux::DVB::DVBT->new() ;
	
	$dvb->set('prune_channels' => 0) if $noprune ;
	$dvb->config_path($config) if $config ;
	$dvb->merge(0) if $clean ;
	
	## Do the scan
	my $freqfile = $ARGV[0] ;
	$dvb->scan_from_file($freqfile) ;


	## All done, just show the results
	my $tuning_href = $dvb->get_tuning_info() ;
	my $channels_aref = $dvb->get_channel_list() ;
	
	my $ok = 1 ;
	print STDERR "Chans\n" ;
	my ($tv, $radio)=(0,0) ;
	foreach my $ch_href (@$channels_aref)
	{
		my $chan = $ch_href->{'channel'} ;
		my $checkstr = "" ;
		if ($check)
		{
			$checkstr .= " ..." ;
			my $tsid = $tuning_href->{'pr'}{$chan}{'tsid'} ;
			if (exists($tuning_href->{'ts'}{$tsid}))
			{
				$checkstr .= "ok" ;
			}
			else
			{
				$checkstr .= "FAILED" ;
				$ok = 0 ;
			}
		}
		printf STDERR "%3d : %-40s %5d-%-5d $ch_href->{type} $checkstr\n", 
			$ch_href->{'channel_num'},
			$chan,
			$tuning_href->{'pr'}{$chan}{'tsid'},
			$tuning_href->{'pr'}{$chan}{'pnr'} ;
		
		if ($ch_href->{type} eq 'tv')
		{
			++$tv ;
		}
		else
		{
			++$radio ;
		}
	}
	printf STDERR "Found %d channels (%d tv, %d other)\n", $tv+$radio, $tv, $radio ;	
	if ($check)
	{
		print STDERR $ok ? "Passed checks\n" : "FAILED checks\n" ;
		if ($tv+$radio == 0)
		{
			$ok = 0 ;
			print STDERR "Failed to find any channels\n" ;
		}
		
		if (!$ok)
		{
			print STDERR <<"ERRMSG" ;
                                                                                                                        
=======================================================================================                                 
Sorry, but your scan failed. Please either contact me or raise a bug report at:                                         
    http://rt.cpan.org/Public/Bug/Report.html?Queue=Linux-DVB-DVBT.                                                     
                                                                                                                        
It would be most helpful if you can attach a debug log of your scan. To do this run:                                    
                                                                                                                        
 # dvbt-scan -debug 15 -verbose 15 $freqfile >scan.log 2>&1                                                             
 # tar cvfz scan.log.tar.gz scan.log                                                                                    
                                                                                                                        
then attach the scan.log.tar.gz file to your email or bug report.                                                       
                                                                                                                        
Thanks.                                                                                                                 
=======================================================================================                                 
                                                                                                                        
ERRMSG
		}
	}

	
	
#=================================================================================
# END
#=================================================================================
__END__

=head1 NAME

dvbt-scan - Initialise DVBT channels

=head1 SYNOPSIS

dvbt-scan [options] frequency_file

Options:

       -debug level         set debug level
       -verbose level       set verbosity level
       -help                brief help message
       -man                 full documentation
       -merge               merge previous scan
       
=head1 OPTIONS

=over 8

=item B<-help>

Print a brief help message and exits.

=item B<-man>

Prints the manual page and exits.

=item B<-verbose>

Set verbosity level. Higher values show more information.

=item B<-debug>

Set debug level. Higher levels show more debugging information (only really of any interest to developers!)

=item B<-clean>

Start a clean scan (i.e. don not merge this scan with previous results). Normally you'll want to merge (the default) so that you scan
in the morning and evening to pick up all the channels (since some are only broadcast morning or evening). However, after a frequency 
change it is best to start from scratch again by using this option. 


=back

=head1 DESCRIPTION

Script that uses the perl Linux::DVB::DVBT package to provide DVB-T adapter functions.
 
Runs the frequency scanning function to search for Freeview channels. Stores the channel information 
into configuration files.

If this program is run as root then the configuration files are stored under B</etc/dvb> and are available
for any user. Otherwise they are stored in B<$HOME/.tv> for just the user.

The frequency file is usually something like: B</usr/share/dvb/dvb-t/uk-Oxford>

The file contents should be something like:

   # Oxford
   # T freq bw fec_hi fec_lo mod transmission-mode guard-interval hierarchy
   T 578000000 8MHz 2/3 NONE QAM64 2k 1/32 NONE

Frequency files are provided by the 'dvb' rpm package available for most distros. Alternatively, if you have kaffeine installed, look in
$HOME/.kde/share/apps/kaffeine/dvb-t. If all else fails you can always get them from my CPAN web space: 

http://www.cpan.org/authors/id/S/SD/SDPRICE/Files/dvb-t.tar.gz

To determine which file to use, check http://www.ukfree.tv/transmitters.php and enter your postcode. 


For full details of the DVBT functions, please see:

   perldoc Linux::DVB::DVBT
 
=cut

	
