#!/opt/bin/perl

#	  perltgd jim16 Thu 14 Dec 13:13:00
#
#	  Copyright (C) 2006 Jim16
#
#	  This is free software; you can redistribute it and/or modify
#	  it under the terms of the GNU General Public License as published by
#	  the Free Software Foundation; either version 2 of the License, or
#	  (at your option) any later version.
#
#	  The software is distributed in the hope that it will be useful,
#	  but WITHOUT ANY WARRANTY; without even the implied warranty of
#	  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	  GNU General Public License for more details.
#
#	  You should have received a copy of the GNU General Public License
#	  along with this software; if not, write to the Free Software
#	  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#

#####################################################################################
#                                 Global Definitions                                #
#####################################################################################

# Define global variables used in program
my $version       = "1.1.0";		# Define the version of the program
my %settings;							# Hash for storing the users settings
my @files;								# Array that stores the files we are interested in for searching
my @favs;								# Stores favourites elements as string Format  - term"\t"channel"\t"day"\t"location"\t"start"\t"end etc..
my @found;								# Stores the events that have been found for sequential joining, number checking and writing to file
my @prevset;							# Stores the events that have previously been set.
my $no_found       = 0;					# Counts the number of events found. Only for display purposes
my $no_repeats     = 0;					# Counts the number of repeats shows found that were dropped
my $events         = 0;					# Used to count the number of events. Only for display purposes
my $timer_clashes  = 0; 				# Records the number of clashes between the timers
my $timer_adjustments = 0;
my $today_yyyymmdd = 0;					# Stores the current date e.g. 20061203
my $previtem;
my $log_string = "";

# Define the files and filenames
$settings{'workdir'} = "/opt/etc/perltgd";
my $timer_file    = "99999999.tgd";		# Filename of timer file
my $settings_file = "perltgd.settings";	# Filename of settings file
my $log_file      = "perltgd.log";		# Filename of log file
my $epg_timers    = "epg_timers.tsv";	# Filename of epg_timers.tsv
my $recplay       = "epg_recplay.tsv";	# Filename of epg_timers.tsv
my $overrun_file  = "overrun.shows";	# Filename of overrun.shows
my $repeat_shows  = "shows.repeat";
my $append_file   = "append.timers";
my $uk_favs       = "UkAutoRemote.txt";

# Variables for new repeat determination method
my %repeat_shows;						# Hash for storing show names and epsisode titles for new repeat detection feature

# Switches used for program. Initially set to not activated
my $download_epg  = 0;					# Whether to download guide
my $search_epg    = 0;					# Whether to search
my $output_timers = 0;					# Whether to output search results to 99999999.tgd document
my $transfer_epg  = 0;					# Whether to transfer files to the PVR
my $reboot_toppy  = 0;					# Whether to reboot topfield when finished
my $make_tgd      = 0;					# Whether to make TGD documents
my $check_con     = 0;					# Whether to check if topfield is connected. Add as only linux method avaliable
my $append_timers = 0;
my $remove_changed = 0;
my $timers_only = 0;
my $debug = 0;

# Hash storing the channel numbers and there character representation
my %channel_hash;

# Variables for storing the overrun channel and status
my $channel = "";					# Store which channel has over run show detected
my $overrun_show = 0;				# Store whether overrun is active
my @overrun_shows;					# Array of overrun shows read in from overrun.shows text document

#####################################################################################
#                                   Start Program                                   #
#####################################################################################

# Read switches from the terminal
foreach( @ARGV ){
	if( $_ eq '-a' || $_ eq '-all' ){
		$download_epg  = 1;
		$search_epg    = 1;
		$output_timers = 1;
		$transfer_epg  = 1;
		$reboot_toppy  = 1;
		$make_tgd      = 1;
		$append_timers = 1;
	} elsif( $_ eq '-at' || $_ eq '-append' ){
		$append_timers = 1;
	} elsif ( $_ eq '-d' || $_ eq '-download' ){
		$download_epg = 1;
	} elsif ( $_ eq '-s' || $_ eq '-search' ){
		$search_epg = 1;
	} elsif ( $_ eq '-o' || $_ eq '-output' ){
		$output_timers = 1;
	} elsif ( $_ eq '-t' || $_ eq '-transfer' ){
		$transfer_epg = 1;
	} elsif ( $_ eq '-r' || $_ eq '-reboot' ){
		$reboot_toppy = 1;
	} elsif ( $_ eq '-mg' || $_ eq '-maketgd' ){
		$make_tgd = 1;
	}  elsif ( $_ eq '-cc' ){
		$check_con = 1;
	} elsif ( $_ =~ /-w/i ){
		my $wd = $_;
		$wd =~ s/-w=//ig;
		$settings{'workdir'} = $wd;
	} elsif ( $_ eq '-rc' || $_ eq '-remove' ){
		$remove_changed = 1;
	} elsif( $_ eq '-onlytimers' ){
		$timers_only = 1;
	} elsif( $_ eq '-debug' ){
		$debug = 1;
	}
}

# Just a bit of information about the time taken to complete
my @time_counter = localtime(time);
my $time_started = (@time_counter[0] + (@time_counter[1]*60) + (@time_counter[2]*60*60));

# Start main part of the program
&readSettings();						# Read the settings file
&printSettings();						# Print out the settings to terminal

# New repeat method defined then read the recorded repeats
&readRepeats() if( $settings{'repeatmethod'} =~ /new/ );
&downloadEPG() if( $download_epg );		# Download data
&makeTGD if( $make_tgd );				# Make the topfield guide

if( $search_epg ){						# Search for favourite shows
	&readFavourites();					# Read favourites and store in favs array
	&storeTGDFileList();				# Get a list of TGD files and store in @files
	&readOverruns();					# Read list of shows that continually overrun for extending time for them and the shows after
	&readTGDDocuments();				# Read all TGD Documents and Search for shows
	&checkNumber();						# Check the number of shows on at the same time. Only allow for 2 tuners
	&recordRepeats() if( $settings{'repeatmethod'} =~ /new/ );	# Output found shows to the repeats file for next time. Auto populate this file with found shows
	&sequentialCheck();					# Join sequential timers together
	&additionalTime();					# Add additional time to any shows that fall between the time range
	&searchLog();						# Print out the results of the search
}

if( $output_timers or $transfer_epg or $reboot_toppy ){
	if( $check_con ){
		# Check that the topfield is connected on the usb bus
		&finish() if( !&toppyConnected() );
	}
	if( $output_timers ){					# Write the timers
		if( @found > 0 ){
			&readEPGTimersTSV();				# Download .tsv from PVR and create TGD Strings
			&removeDuplicates();				# Remove duplicates from found shows
			&removeOutdated();					# Remove previously set timers that have past from @prevset
			if( $remove_changed ){
				&removeDeadTimers();				# Setup to remove timers from PVR
			}
			&outputTimersScreen();				# Output which timers are to be set
			&outputTimers();					# Write the 99999999.tgd
		}
	}
	if( $transfer_epg ){					# Transfer files to the topfield
		&transferEPG();
	}
	if( $reboot_toppy ){					# Reboot topfield if able to. This will mean timers will be set on reboot
		if( $settings{'reboot'} ){			# If we have a reboot string then reboot
			&rebootToppy();
		} else {
			&printOut("No reboot string defined\nNo reboot performed\n");
		}
	}
}
# Print final information out such as time taken
&finish();

# Close the program
exit;

#####################################################################################
#                                  Main Components                                  #
#####################################################################################

# function to read settings from settings.info into hash settings
sub readSettings(){
	if( -e "$settings{'workdir'}/$settings_file" and -r "$settings{'workdir'}/$settings_file" ){
		open(SETTINGS, "$settings{'workdir'}/$settings_file");
		while (<SETTINGS>) { 
			if( $_ !~ /^\#/ ){
				chomp; 
				(my $key, my $value) = split(/::/, $_); 
				$settings{$key} = $value;
			}
		}
		close SETTINGS;
		if( $settings{'lcnname'} ){
			&createChannelHash($settings{'lcnname'});
		}
	} else {
		&printOut("ERROR ::: Settings file ( $settings_file ) doesn't exists or can't be read. Please ensure it is located in the working directory and has readable permissions.\n\n");
		exit;	# Stop processing if we can't get the settings
	}
}

# function to read repeats from shows.repeat hash repeat_shows
sub readRepeats(){
	&printOut("\n    Reading Repeats File\n\n");
	if( -e "$settings{'workdir'}/$repeat_shows" and -r "$settings{'workdir'}/$repeat_shows" ){
		open(REPEATS, "$settings{'workdir'}/$repeat_shows");
		while (<REPEATS>) { 
			if( $_ !~ /^\#/ ){
				chomp; 
				(my $key, my $value) = split(/\t/, $_); 
				$repeat_shows{$key} = $value;
			}
		}
		close REPEATS;
		&printOut("        Recorded Repeats        ::: ".keys(%repeat_shows)."\n\n");
	}
}

# function to record the repeats out to the show.repeats file
sub recordRepeats(){
	&printOut("\n    Updating $repeat_shows\n");
	foreach my $founditem( @found ){
		my $nm = &createName( $founditem );
		if( $nm =~ /-/ ){	# Assume that if - is preswent is show - episode
			if( !exists($repeat_shows{$nm}) ){			
				$repeat_shows{$nm} = &createDate($founditem);
			}
		}
	}
	# Lets output these repeats events to file for use next time
	open( REPEATS, ">$settings{'workdir'}/$repeat_shows" );
	foreach my $repeats( keys %repeat_shows ){
		print REPEATS "$repeats\t".$repeat_shows{$repeats}."\n";
	}
}

# function that calls the grabber and make guide. Users could just have as part of there shell script
sub downloadEPG(){
	&printOut("Downloading EPG\n\n");
	open TMP, "$settings{'grabber'} |";
	while ( <TMP> ){
		&printOut($_);
	}
	close TMP;
}

# function to make the topfield guide
sub makeTGD(){
	&printOut("Making Topield TGD Documents\n");
	&printOut("\nRemoving OLD .tgd Documents\n\n");
	open TMP, "rm $settings{'outputdir'}/*.tgd |";
	while ( <TMP> ){
		&printOut($_);
	}
	open TMP, "$settings{'makeguide'} |";
	while ( <TMP> ){
		&printOut($_);
	}
	close TMP;
}

# Sub called as part of PVR favourite append
sub favouriteExists(){
	my $favstring = shift @_;
	my @fav_itemcheck = split(/\t/, $favstring );
	foreach( @favs ){
		@fav_item = split(/\t/, $_ );
		if( &trim(@fav_itemcheck[0]) eq &trim(@fav_item[0]) ){	# Check that the same search term doesn't exists already
			return 1;
		}
	}
	return 0;
}

# function that reads favourites from file and stores them in favs array as a string.
sub readFavourites(){
	if( $settings{'downloadfav'} ){	# If we have the ability to grab from autostart see if we can get UKAutoRemote.txt
		# Read from Auto Start directory for Uk Auto file
		&printOut("\n    Downloading Favourites From PVR\n\n");
		if( $check_con ){
			# Check that the topfield is connected on the usb bus
			&finish() if( !&toppyConnected() );
		}
		open TMP, "$settings{'downloadfav'} |";
		while ( <TMP> ){
			&printOut($_);
		}
		close TMP;
	}
	&printOut("    Reading Favourites File\n\n");
	if( -e "$settings{'workdir'}/$settings{'favfile'}" and -r "$settings{'workdir'}/$settings{'favfile'}" ){
		open( FAVOURITES, "$settings{'workdir'}/$settings{'favfile'}" );
		while ( <FAVOURITES> ){	
			if( $_ !~ /^\#/ && $_ !~ /^ /){
				chomp;
				push(@favs,$_);
			}
		}
		close FAVOURITES;
	}
	# Custom sorting so when searching higher priority show are searched for first
	# This will mean that when something is found it will have the highest priority
	# it can. Otherwise a keyword with a lower priority may find the show before
	# another keyword with greater priority and it may be dropped.
	@favs = sort {
		@a1 = split(/\t/,$a);
		@b1 = split(/\t/,$b);
		if( $a1[6] =~ $b1[6] ){
			# Same priority so sort by name
			return (lc($a) cmp lc($b));
		}
		if( $a1[6] > $b1[6] ){
			return -1;
		} else {
			return 1;
		}
	} @favs;
	&printOut("        Number of Favourites    ::: ".@favs."\n");
}

# function that reads all documents from files array and calls search for processing favourites on each event
sub readTGDDocuments(){
	&printOut("\n    Reading Documents and Searching for Favourite Shows\n");
	foreach ( @files ){
		&printOut("\n\tProcessing File ::: $_\n\n");
		chomp;
		if( -e "$settings{'outputdir'}/$_" && -r "$settings{'outputdir'}/$_" ){	# Check the file exists
			open( TGDFILE, "$settings{'outputdir'}/$_" );
			while ( <TGDFILE> ){
				chomp;
				&isShowOverrun($_);
				&search($_); 
				$events++; 
				$previtem = $_; 
			}
			close TGDFILE;
			$overrun_show = 0;
			$channel = "";
		}
	}
}

# function that recieves a line of TGD format and looks for favourite matches.
sub search(){
	my $tgd = shift @_;
	$tgd =~ s/\n//ig;
	my @tgdobj = split(/\t/, $tgd); # Split into array...
	# Add the time to the duration here if overrun to make life easy
	if( $overrun_show ){
		@tgdobj[2] += $settings{'overrun'};
		$tgd = join("\t", @tgdobj );
	}
	# Go thru each favourite and look for a match. If previtem is matched set overrun to 1 ( or true ).
	for( my $i = 0; $i < @favs; $i++ ){
		my @favobj = split(/\t/, @favs[$i] ); # Split fav into array for processing
		if( @favobj[1] =~ /All/ || $tgdobj[0] =~ /^@favobj[1]$/ ){
			my $pref = $favobj[6];
			my $adjustable;
			if( $favobj[8] =~ 1 ){
				$adjustable = 1;
			} else {
				$adjustable = 0;
			}
			# This extracts the year month and day from the date time string
			my @temp = split(/ /,$tgdobj[1]);
			my @date = split(/-/,@temp[0]);
			# See if show can be search for with the favourite element
			if( ( $favobj[2] =~ /All/i ) or
		 	    ( $favobj[2] =~ /Sun/i and &dayOfWeek(@date[0],@date[1],@date[2]) =~ /0/ ) or
			    ( $favobj[2] =~ /Mon/i and &dayOfWeek(@date[0],@date[1],@date[2]) =~ /1/ ) or
			    ( $favobj[2] =~ /Tue/i and &dayOfWeek(@date[0],@date[1],@date[2]) =~ /2/ ) or
			    ( $favobj[2] =~ /Wed/i and &dayOfWeek(@date[0],@date[1],@date[2]) =~ /3/ ) or
			    ( $favobj[2] =~ /Thu/i and &dayOfWeek(@date[0],@date[1],@date[2]) =~ /4/ ) or
			    ( $favobj[2] =~ /Fri/i and &dayOfWeek(@date[0],@date[1],@date[2]) =~ /5/ ) or
			    ( $favobj[2] =~ /Sat/i and &dayOfWeek(@date[0],@date[1],@date[2]) =~ /6/ ) or
			    ( $favobj[2] =~ /WeekDay/i and 
			    				(&dayOfWeek(@date[0],@date[1],@date[2]) !~ /0/ and &dayOfWeek(@date[0],@date[1],@date[2]) !~ /6/ )) or
			    ( $favobj[2] =~ /WeekEnd/i and 
			    				(&dayOfWeek(@date[0],@date[1],@date[2]) =~ /0/ or &dayOfWeek(@date[0],@date[1],@date[2]) =~ /6/ )) or
				# For Regular expression Matching
				( &dayOfWeek(@date[0],@date[1],@date[2]) =~ /$favobj[2]/g )
				){
				# Match for location all
				if( $favobj[3] =~ /All/i ){ 
					if( $tgd =~ /$favobj[0]/i ){
						if( &timeCheck($favobj[4],$favobj[5],$tgdobj[1]) ){
							if( $favobj[7] =~ 1 ){
								if( $tgd =~ /$settings{'repeatflag'}/g ){
									$no_repeats++;
									&printOut("\t\tFound ::: $tgdobj[3] [$favobj[0]]\t- No Record Repeat\n");
									next;
								} else {
									if( $repeat_shows{&createName($tgd)} && $repeat_shows{&createName($tgd)} < $today_yyyymmdd  ){
										$no_repeats++;
										&printOut("\t\tFound ::: $tgdobj[3] [$favobj[0]]\t- No Record Repeat\n");
										next;
									} else {
										$no_found++; 
										push(@found,$tgd."\t".$pref."\t".$adjustable); 
										&printOut("\t\tFound ::: $tgdobj[3] [$favobj[0]]\n");
										return;
									}
								}
							} else {
								$no_found++;
								push(@found,$tgd."\t".$pref."\t".$adjustable); 
								&printOut("\t\tFound ::: $tgdobj[3] [$favobj[0]]\n");
								return;	# Return now we have found show so we dont find same event twice
							}
						}
					}
				}
				# Match for TitleExact
				elsif ( $favobj[3] eq "TitleExact" ){
					if( $tgdobj[3] eq $favobj[0] ){ 
						if( &timeCheck($favobj[4],$favobj[5],$tgdobj[1]) ){
							if( $favobj[7] =~ 1 ){
								if( $tgd =~ /$settings{'repeatflag'}/g ){
									$no_repeats++;
									&printOut("\t\tFound ::: $tgdobj[3] [$favobj[0]]\t- No Record Repeat\n");
									next;
								} else {
									if( $repeat_shows{&createName($tgd)} && $repeat_shows{&createName($tgd)} < $today_yyyymmdd ){
										$no_repeats++;
										&printOut("\t\tFound ::: $tgdobj[3] [$favobj[0]]\t- No Record Repeat\n");
										next;
									} else {
										$no_found++; 
										push(@found,$tgd."\t".$pref."\t".$adjustable); 
										&printOut("\t\tFound ::: $tgdobj[3] [$favobj[0]]\n");
										return;
									}
								}
							} else {
								$no_found++; 
								push(@found,$tgd."\t".$pref."\t".$adjustable); 
								&printOut("\t\tFound ::: $tgdobj[3] [$favobj[0]]\n");
								return;
							}
						}
					}
					next;
				}
				# Match for SubTitle.
				elsif ( $favobj[3] =~ /Subtitle/i ){ 
					if( $tgdobj[4] =~ /$favobj[0]/i ){ 
						if( &timeCheck($favobj[4],$favobj[5],$tgdobj[1]) ){
							if( $favobj[7] =~ 1 ){
								if( $tgd =~ /$settings{'repeatflag'}/g ){
									$no_repeats++;
									&printOut("\t\tFound ::: $tgdobj[3] [$favobj[0]]\t- No Record Repeat\n");
									next;
								} else {
									if( $repeat_shows{&createName($tgd)} && $repeat_shows{&createName($tgd)} < $today_yyyymmdd  ){
										$no_repeats++;
										&printOut("\t\tFound ::: $tgdobj[3] [$favobj[0]]\t- No Record Repeat\n");
										next;
									} else {
										$no_found++; 
										push(@found,$tgd."\t".$pref."\t".$adjustable); 
										&printOut("\t\tFound ::: $tgdobj[3] [$favobj[0]]\n");
										return;
									}
								}
							} else {
								$no_found++; 
								push(@found,$tgd."\t".$pref."\t".$adjustable); 
								&printOut("\t\tFound ::: $tgdobj[3] [$favobj[0]]\n");
								return;
							}
						}
					}
					next;
				}
				# Match for Title.
				elsif ( $favobj[3] =~ /Title/i ){
					if( $tgdobj[3] =~ /$favobj[0]/i ){ 
						if( &timeCheck($favobj[4],$favobj[5],$tgdobj[1]) ){
							if( $favobj[7] && $settings{'repeatflag'} ){
								if( $tgd =~ /$settings{'repeatflag'}/g ){
									$no_repeats++;
									&printOut("\t\tFound ::: $tgdobj[3] [$favobj[0]]\t- No Record Repeat\n");
									next;
								} else {
									if( $repeat_shows{&createName($tgd)} && $repeat_shows{&createName($tgd)} < $today_yyyymmdd  ){
										$no_repeats++;
										&printOut("\t\tFound ::: $tgdobj[3] [$favobj[0]]\t- No Record Repeat\n");
										next;
									} else {
										$no_found++; 
										push(@found,$tgd."\t".$pref."\t".$adjustable); 
										&printOut("\t\tFound ::: $tgdobj[3] [$favobj[0]]\n");
										return;
									}
								}
							} else {
								$no_found++; 
								push(@found,$tgd."\t".$pref."\t".$adjustable); 
								&printOut("\t\tFound ::: $tgdobj[3] [$favobj[0]]\n");
								return;
							}
						}
					}
					next;
				}
				# Match for Description.
				elsif ( $favobj[3] =~ /Desc/i ){
					if( $tgdobj[5] =~ /$favobj[0]/i ){ 
						if( &timeCheck($favobj[4],$favobj[5],$tgdobj[1]) ){
							if( $favobj[7] =~ 1 ){
								if( $tgd =~ /$settings{'repeatflag'}/g ){
									$no_repeats++;
									&printOut("\t\tFound ::: $tgdobj[3] [$i]\t- No Record Repeat\n");
									next;
								} else {
									if( $repeat_shows{&createName($tgd)} && $repeat_shows{&createName($tgd)} < $today_yyyymmdd  ){
										$no_repeats++;
										&printOut("\t\tFound ::: $tgdobj[3] [$i]\t- No Record Repeat\n");
										next;
									} else {
										$no_found++; 
										push(@found,$tgd."\t".$pref."\t".$adjustable); 
										&printOut("\t\tFound ::: $tgdobj[3] [$i]\n");
										return;
									}
								}
							} else {
								$no_found++; 
								push(@found,$tgd."\t".$pref."\t".$adjustable); 
								&printOut("\t\tFound ::: $tgdobj[3] [$i]\n");
								return;
							}
						}
					}
					next;
				}
			}
		}
	}
}

# function to add more time to the shows duration if it falls between the additional time start and end
sub additionalTime(){
	&printOut("\n    Adding Additional Time\n\n");
	my $adjustments = 0;
	for( my $i=0; $i<@found; $i++ ){	# Cycle thru each found and add more time if needed
		my @show       = split(/\t/,@found[$i]);	# Split event up in array
		my $start_time = &showStartMinutes($show[1]); # = (@time[0]*60) + @time[1];
		if( $start_time >= $settings{'addtimestart'} && $start_time <= $settings{'addtimeend'} 
			||
			$start_time + @show[2] >= $settings{'addtimestart'} && $start_time <= $settings{'addtimeend'} ){
			my $wasdur = @show[2];
			@show[2] += $settings{'addtime'};
			$adjustments++;
			&printOut("\t    @show[3] - Was $wasdur, Now @show[2] Minutes\n");
			@found[$i] = join("\t",@show);
		}
	}
	# If we have adjusted any timers then check for conflicts and join any over lapping timers
	if( $adjustments ){
		&printOut("\n    Rechecking timer conflicts and joining after adjustments\n");
		&checkNumber();
		&sequentialCheck();
	}
}

# function that looks at every found event and compare it with previously found. 
sub removeDuplicates(){
	&printOut("    Removing Duplicate Timers\n\n");
	my @delete;
	my $counter = 0;
	while( @prevset ){
		my $previtem = pop(@prevset);				# Get the top element of previously set
		# Grab a copy and do any changes need for comparison
		my $compare = &trim($previtem);	
		my $isfound = 0;							# Say we haven't found the shows duplicate
		for( my $i=0; $i<@found; $i++ ){				# Check against all previously set timers
			my @foundobj = split(/\t/, @found[$i]);
			my $timer_title = &trim(&createTitle(@found[$i]));
			my $datetime = &createDateTime(@foundobj[1]);
			my $duration = $foundobj[2] + -$settings{'startbuffer'} + $settings{'endbuffer'};
			my $founditem = "@foundobj[0]\t$datetime\t$duration\t".substr($timer_title,0,59); 
			#my $founditem = "@foundobj[0]\t$datetime\t$duration\t$timer_title";
			if( /\Q$founditem\E/ =~ /\Q$compare\E/ ){
				$isfound = 1;	# Say that this item is found
				$counter++;	# Count how may items are found to have been previously set
				splice(@found,$i,1);	# Remove element from array
				next;
			}
			# This is a hack as wierd shit happens and not all match with the first expression when they should
			elsif( $founditem eq $compare ){
				$isfound = 1;	# Say that this item is found
				$counter++;	# Count how may items are found to have been previously set
				splice(@found,$i,1);	# Remove element from array
				next;
			}
		}
		if( !$isfound ){
			push(@delete, $previtem);
		}	# If show wasn't found then put on stack to delete timer
	}
	@prevset = @delete;		# Set prev set to delete array
	&printOut("        Number of Duplicates Removed ::: $counter\n\n");
}

sub removeOutdated(){
	&printOut("    Removing Outdated Timers\n\n");
	# Remove all times that are before now :)
	my @time = localtime(time);	# Get the local time of the computer
	my $nowyear = sprintf('%04d', (@time[5]+1900));
	my $nowmonth = sprintf('%02d', (@time[4]+1));
	my $nowday = sprintf('%02d', (@time[3]));
	my $datenow = "$nowyear$nowmonth$nowday";
	my $prevsetsize = @prevset;
	&printOut("\tTimers Previously Set ::: $prevsetsize\n");
	my @newprev;
	foreach( @prevset ){
		my @prevobj = split(/\t/, $_);				# Break up into segments
		my $d = substr(@prevobj[1],0,10);			# Store the date for the show previously set
		my $h = substr(@prevobj[1],11,2);			# Store the hour which the show is one
		my $m = substr(@prevobj[1],14,2);			# Not used atm
		$d =~ s/-//gi;
		if( $d > $datenow ){
			push( @newprev, $_ );
			&printOut("\n\t\t    @prevobj[3]");
		} elsif( $d =~ $datenow ){
			if( @time[ 2 ] <= $h ){
				push( @newprev, $_ );
			} else {
				&printOut("\n\t\t    @prevobj[3] ( Outdated )");
			}
		} else {
			&printOut("\n\t\t    @prevobj[3] ( Outdated )");
		}
	}
	@prevset = @newprev;
	my $size = $prevsetsize-@prevset;
	if( $size > 0 ){
		&printOut("\n            Previously Set Timers Removed ::: $size \n");
	} else {
		&printOut("\n");
	}
}

# Set delete flag for any timers that were set previously set and not found now
sub removeDeadTimers(){
	&printOut("    Removing Changed Timers\n");
	my $removed = 0;
	for( my $i=0; $i<@prevset; $i++ ){												# Go thru every item and add delete flag to end of string
		my @prevobj = split(/\t/, @prevset[$i]);								# Break up into segments
		if( @prevobj[2] > 5 ){	# Allow 5 minute time sync timers
			# Store replacing the previous entry
			@prevset[$i] = "@prevobj[0]\t@prevobj[1]\t@prevobj[2]\t@prevobj[3]\t@prevobj[4]\t\t\tD";
			&printOut("\n        Removing ::: @prevobj[1]   @prevobj[3]");
			$removed++;
		} else {
			splice(@prevset,$i,1);	# Remove from the array as we don't need this one
			$i = -1;
		}
	}
	my $size = @prevset;
	if( $removed ){
		&printOut("\n");
	}
	&printOut("\n        Total Number of Timers to be Deleted ::: $size\n");
}

# function that writes the 99999999.tgd document for setting timers.
# If not joined will attempt to have show (user delimeter from settings) episode as title of timer.
sub outputTimers(){
	&printOut("\n    Writing Timers to 99999999.tgd.\n\n");
	&printOut("        Timers to be set ::: ".@found."\n");
	&printOut("        Timers to remove ::: ".@prevset."\n");
	if( @found > 0 || @prevset > 0 ){	# Only write timer file if we actually have something to set.
		open ( TIMERFILE, ">$settings{'outputdir'}/$timer_file" );
		@prevset = sort(@prevset);
		for( my $p = 0; $p<@prevset; $p++ ){
			print TIMERFILE "@prevset[$p]\n";		
		}
		@found = sort(@found);
		for( my $i = 0; $i<@found; $i++ ){
			my @timerobj = split(/\t/, @found[$i]);
			my $timer_title = &createTitle(@found[$i]);
			my $buffer = "$settings{'startbuffer'} $settings{'endbuffer'}";
			print TIMERFILE "@timerobj[0]\t@timerobj[1]\t@timerobj[2]\t$timer_title\t@timerobj[4]\t\t\t$buffer\n";
		}
		if( $append_timers ){
			if( -e "$settings{'workdir'}/$append_file" && -r "$settings{'workdir'}/$append_file" ){
				my $append_count = 0;
				open( APPEND, "$settings{'workdir'}/$append_file" );
					while ( <APPEND> ){	
					if( $_ !~ /^\#/ && $_ !~ /^ /){
						chomp;
						my @timers = split(/\t/, $_);				# Break up into segments
		 				my $dow = &dayOfWeek((1900 + @time_counter[5]),(@time_counter[4] + 1),@time_counter[3]);
		 				my $date_string;
					 	my $diff = $dow - @timers[1];
					 	if( $diff =~ 0 ){	# Same dow so we have the date
					 		$date_string = sprintf('%04d',(1900 + @time_counter[5]))."-".sprintf('%02d',(@time_counter[4] + 1))."-".sprintf('%02d',(@time_counter[3]));
					 	} else {
					 		my @date = ( (1900 + @time_counter[5]),(@time_counter[4] + 1),@time_counter[3]);
					 		if( $diff > 0 ){
					 			@date = &subtractDay($date[0],$date[1],$date[2],$diff);
					 			@date = &subtractDay($date[0],$date[1],$date[2],7);
					 		} else {
					 			@date = &subtractDay($date[0],$date[1],$date[2],$diff);
					 		}
					 		$date_string = sprintf('%04d',$date[0])."-".sprintf('%02d',$date[1])."-".sprintf('%02d',$date[2]);					 		
					 	}
					 	if( $date_string ){
							print TIMERFILE "$timers[0]\t$date_string $timers[2]\t$timers[3]\t$timers[4]\t\t\t\t-00 +00\n";
							$append_count++;
					 	}
					}
				}
				close APPEND;
				&printOut("        Timers to append ::: ".$append_count."\n");
			}
		}
		close TIMERFILE;
		&printOut("\n        Finished writing timers file.\n\n");
	} else {
		&printOut("\n\t    No timers to write.\n\n");
		if( -e "$settings{'outputdir'}/$timer_file" ){
			# Remove the timer file if its present
			`rm $settings{'outputdir'}/$timer_file`;
		}
	}
}

# function to transfer files to the topfield
# Slighlty different as i here that the opendir, readdir is missing from microperl
# I have replaced with system call and parsing with regexp for list of files
sub transferEPG(){
	&printOut("    Transfering TGD Documents\n\n");
	@files = split(/\n/, `ls -1 $settings{'outputdir'}`);
	@files = sort( @files );
	my @time = localtime(time);	# Get the local time of the computer
	my $nowyear = sprintf('%04d', (@time[5]+1900));
	my $nowmonth = sprintf('%02d', (@time[4]+1));
	my $nowday = sprintf('%02d', (@time[3]));
	my $datenow = "$nowyear$nowmonth$nowday";
	foreach my $file (@files) {
		if( $file =~ /.tgd/ ){
			my $tmp = $file;
			$tmp =~ s/\.tgd//g;
			if( $tmp < $datenow ){ next; }
			if( $timers_only ){
				if( $file =~ /$timer_file/ ){
					my $transfer_string = $settings{'transfer'};
					# Replace all the <> tags with the repected values from settings and files pointer
					$transfer_string =~ s/<CURRENT>/$settings{'workdir'}/ig;
					$transfer_string =~ s/<TGD>/$settings{'tgddir'}/ig;
					$transfer_string =~ s/<OUTPUT>/$settings{'outputdir'}/ig;
					$transfer_string =~ s/<FILE>/$file/ig;
					$transfer_string =~ s/<TFDIR>/$settings{'tfdir'}/ig;
					&printOut("\t\tTransfering ::: $file\n");
					`$transfer_string`;
				}
			} else {
				my $transfer_string = $settings{'transfer'};
				# Replace all the <> tags with the repected values from settings and files pointer
				$transfer_string =~ s/<CURRENT>/$settings{'workdir'}/ig;
				$transfer_string =~ s/<TGD>/$settings{'tgddir'}/ig;
				$transfer_string =~ s/<OUTPUT>/$settings{'outputdir'}/ig;
				$transfer_string =~ s/<FILE>/$file/ig;
				$transfer_string =~ s/<TFDIR>/$settings{'tfdir'}/ig;
				&printOut("\t\tTransfering ::: $file\n");
				`$transfer_string`;
			}
		}
	}
}

# Reboot the topfield if we are not recording
sub rebootToppy(){
	if( &isRecording() ){
		&printOut("\n\tCurrently Active - No Reboot Performed\n\n");
	} else {
		&printOut("\n\tRebooting Toppy\n");
		`$settings{'reboot'}`;
	}
}

# function to read in overrun shows and store in the array
sub readOverruns(){
	&printOut("\n    Reading Overrun Shows\n");
	if( -e "$settings{'workdir'}/$overrun_file" and -r "$settings{'workdir'}/$overrun_file" ){
		open( FILE, "$settings{'workdir'}/$overrun_file" );
		while( <FILE> ){
			chomp;
			if( $_ && $_ !~ /^\#/ ){
				push( @overrun_shows, $_ );
			}
		}
		close FILE;
		&printOut("\n        Number of overrun shows ::: ".@overrun_shows."\n");
	} else {
		&printOut("\n    Unable to read overrun list. Please ensure that it is in the working directory and readable\n");
	}
}

# function to read the tsv file generated by EPG_Uploader
sub readEPGTimersTSV(){
	&printOut("\n    Downloading currently set timers\n\n");
	my $download_string = $settings{'download'};
	$download_string =~ s/<CURRENT>/$settings{'workdir'}/ig;
	$download_string =~ s/<TGD>/$settings{'tgddir'}/ig;
	$download_string =~ s/<OUTPUT>/$settings{'outputdir'}/ig;
	$download_string =~ s/<FILE>/$epg_timers/ig;
	$download_string =~ s/<TFDIR>/$settings{'tfdir'}/ig;
	# Download the file from the unit
	`$download_string`;
	# Lets open this file and read the contents
	if( -e "$settings{'outputdir'}/$epg_timers" and -r "$settings{'outputdir'}/$epg_timers" ){
		open( FILE, "$settings{'outputdir'}/$epg_timers" );
		while( <FILE> ){
			chomp;
			if( $_ !~ /^fileName/i && $_ !~ /$settings{'ignoretimers'}/i ){
				my $tgdFor = &buildTGDStringFromEPGTimers( $_ );
				&printOut("\t\t    $tgdFor\n");
				if( $tgdFor ){
					push( @prevset, $tgdFor );
				}
			}
		}
	} else {
		&printOut( "        $epg_timers from local not found or readable. Please check\n\n");
	}
}

# function to get an array of files to be read in.
sub storeTGDFileList(){
	$today_yyyymmdd = sprintf("%04d",( 1900 + @time_counter[5])).sprintf("%02d",( 1 + @time_counter[4])).sprintf("%02d",( @time_counter[3])).".tgd";
	@files = split(/\n/, `ls -1 $settings{'outputdir'}`);
	@files = sort( @files );
	for( my $i = 0; $i<@files; $i++ ){
		# Remove any timer files
		if( @files[$i] =~ /^9/ ){
			splice(@files,$i,1);
			$i=0;
		}
		if( @files[$i] !~ /^[0-9]/ ){
			splice(@files,$i,1);
			$i=0;
		}
		# Remove anyfiles before today
		if( @files[$i] < $today_yyyymmdd ){
			splice(@files,$i,1);
			$i=0;
		}
	}
	if( @files < 1 ){
		&printOut( "        No .tgd files found. Will quit\n\n");
		sleep 2;
		exit;
	}
	return undef;
}

# function to strip whitespace from a string
sub trim(){
	my $string = shift;
	$string =~ s/^\s+//;
	$string =~ s/\s+$//;
	return $string;
}

####################################################################################
#                                  Timer Functions                                  #
#####################################################################################

# function that checks for sequential timers and joins them together as show1 (delimeter from settings) show2 etc.
sub sequentialCheck(){
	&printOut("\n    Sequential Joining\n\n");
	for( my $i = 0; $i<@found; $i++ ){									# Go thru each and every element is found
		my @show1 = split(/\t/, @found[$i]);						# Store the current show
		my $show1start = &createStartTime(@found[$i]);				# Create the starting time
		my $show1end = &createEndTime(@found[$i]);					# Create the ending time
		for( my $j = 0; $j<@found; $j++ ){
			if( $i !~ $j ){											# Check we are not looking at the same event
				my @show2 = split(/\t/, @found[$j]);
				if( @show1[0] eq @show2[0] ){						# To join must be on the same channel
					my $show2start = &createStartTime(@found[$j]);
					my $show2end = &createEndTime(@found[$j]);
					if( $show2start <= $show1end && $show2end >= $show1end ){
						# Need to join here and reset i and j to begin search again. Irriative solution
						my $newduration;
						if( substr(&createStartTime(@found[$i]),0,8) eq substr(&createEndTime(@found[$j]),0,8) ){
							# Same date so subtract show2end and show1start to get duration. This will stop any compounding of duration by overrun shows
							$newduration = (&createEndTime(@found[$j])-&createStartTime(@found[$i])) + $settings{'startbuffer'} - $settings{'endbuffer'};
						} else {
							$newduration = @show1[2] + @show2[2];	# Add duration
						}
						my $priority = @show1[8];
						if( @show2[8] > $priority ){
							$priority = @show2[8];
						}
						my $newtitle = "@show1[3] $settings{'join'} @show2[3]";
						@found[$i] = "@show1[0]\t@show1[1]\t$newduration\t$newtitle\tJoined TGD\t\tN\t\t$priority";
						&printOut("\t\tJoined ::: $newtitle\n");
						splice(@found,$j,1);
						$i = -1;
						$j = @found;	# Stop searching and allow show1 and show2 to reset...
					}
				}
			}
		}
	}
}

sub adjustStartTime(){
	my $pointer = shift @_;
	my $adjustment = shift @_;
	my @show = split("\t",@found[$pointer]);
	my $startat = &createStartTime(@found[$pointer]);
	$startat += (-$adjustment);
	# Date
	my $year = sprintf('%04d',substr( $startat, 0, 4 ));
	my $month = sprintf('%02d',substr( $startat, 4, 2 ));
	my $day = sprintf('%02d',substr( $startat, 6, 2 ));
	# Minutes
	my $minutes = substr( $startat, 8, 4 );
	my $mins = sprintf('%02d',($minutes%60));
	my $hr = sprintf('%02d',(($minutes-$mins)/60));
	my $newdatetime = "$year-$month-$day $hr\:$mins";
	$show[1] = $newdatetime;
	$show[9] = 0;	# Set to no adjust to only allow 1 adjustment to attempt to fix the problem
	@found[$pointer] = join("\t",@show);
	return;
}

sub adjustStart(){
	my $pointer = shift @_;
	my $adjustment = shift @_;
	my @show = split("\t",@found[$pointer]);
	my $startat = &createStartTime(@found[$pointer]);
	$startat += (-$adjustment*2);
	# Date
	my $year = sprintf('%04d',substr( $startat, 0, 4 ));
	my $month = sprintf('%02d',substr( $startat, 4, 2 ));
	my $day = sprintf('%02d',substr( $startat, 6, 2 ));
	# Minutes
	my $minutes = substr( $startat, 8, 4 );
	my $mins = sprintf('%02d',($minutes%60));
	my $hr = sprintf('%02d',(($minutes-$mins)/60));
	my $newdatetime = "$year-$month-$day $hr\:$mins";
	$show[1] = $newdatetime;
	$show[9] = 0;	# Set to no adjust to only allow 1 adjustment to attempt to fix the problem
	@found[$pointer] = join("\t",@show);
	return;
}

# Functioon to adjust the duration string of a tgd object in the found array
# In here we will flag the found element as no change to stop any further adjustments
sub adjustDuration(){
	my $pointer = shift @_;
	my $adjustment = shift @_;
	my @show = split("\t",@found[$pointer]);
	$show[2] -= $adjustment;
	$show[2]--;
	$show[9] = 0;	# Set to no adjust to only allow 1 adjustment to attempt to fix the problem
	@found[$pointer] = join("\t",@show);
	return;
}

# function that checks for too many timers at a time. Since the topfield has 2 tuners is needed.
sub checkNumber(){
	&printOut("\n    Checking Timers\n");
	my $tuner2 = 0;
	my $tuner2show;
	my $tuner2channel;
	my $tuner2start;
	my $tuner2end;
	my $tuner2priority = 0;
	my $tuner2showpointer;
	my $tuner2adjust = 0;
	my $tmp_adj = 0;
	for( my $i = 0; $i < @found; $i++ ){
		my @show1 = split(/\t/, @found[$i]);	# Store the current show
		my $show1start = &createStartTime(@found[$i]);	# Create the starting time
		my $show1end = &createEndTime(@found[$i]);		# Create the ending time
		for( my $j = 0; $j < @found; $j++ ){
			$tmp_adj++;
			if( $i !~ $j ){	# Not pointing at same show
				my @show2 = split(/\t/, @found[$j]);	# Store show to elements in array
				my $show2start = &createStartTime(@found[$j]); # Create the starting time
				my $show2end = &createEndTime(@found[$j]);	# Create ending string.
				if( !(@show1[0] eq @show2[0]) && !($tuner2channel eq @show2[0]) && !($tuner2channel eq @show1[0]) ){	# Check that its not on the same channel
#				if( @show1[0] !~ @show2[0] && $tuner2channel !~ @show2[0] && $tuner2channel !~ @show1[0] ){	# Check that its not on the same channel
					if( ($show2start <= $show1end && $show2end >= $show1start ) ||
						($show2start >= $show1start && $show2end <= $show1start)){
						if( $tuner2 ){	# Check if the show on tuner2 clashes with any of these times
							if(
#								[ Show 2 ]
#									[ Tuner 2 ]
								( $show2start <= $tuner2start && $show2end <= $tuner2end && $show2end >= $tuner2start )
								||
#								[ Tuner 2 ]
#									[ Show 2 ]								
								( $tuner2start <= $show2start && $tuner2end <= $show2end && $tuner2end >= $show2start )
				
								){
								if( @show1[9] && @show2[9] && $tuner2adjust ){
									# Everything is adjustable so lets see how to best change our timers
									&printOut("\n\t$tuner2show, @show1[3] and @show2[3] Adjustable\n\n");
									# Determine which show starts first
									if( $show1start <= $show2start && $show1start < $tuner2start ){
										if( $show2start <= $tuner2start ){
											&adjustDuration($i,$settings{'endbuffer'});
											&adjustStart($j,$settings{'startbuffer'});
											@show1 = split(/\t/, @found[$i]);
											@show2 = split(/\t/, @found[$j]);
											my @s1 = split(/\t/, @found[$i]);	# Store the current show
											my @s2 = split(/\t/, @found[$j]);	# Store the current show
											&printOut("\t\t@s1[3] now @s1[2] Mins starting at @s1[1] with $settings{'startbuffer'}, $settings{'endbuffer'} buffering\n");
											&printOut("\t\t@s2[3] now @s2[2] Mins starting at @s2[1] with $settings{'startbuffer'}, $settings{'endbuffer'} buffering\n");
											$timer_adjustments++;
										} else {
											&adjustDuration($i,$settings{'endbuffer'});
											&adjustStart($tuner2showpointer,$settings{'startbuffer'});
											$tuner2start = &createStartTime(@found[$tuner2showpointer]); # Create the starting time
											$tuner2end = &createEndTime(@found[$tuner2showpointer]);	# Create ending string.
											@show1 = split(/\t/, @found[$i]);
											my @s1 = split(/\t/, @found[$tuner2showpointer]);	# Store the current show
											my @s2 = split(/\t/, @found[$i]);	# Store the current show
											&printOut("\t\t@s1[3] now @s1[2] Mins starting at @s1[1] with $settings{'startbuffer'}, $settings{'endbuffer'} buffering\n");
											&printOut("\t\t@s2[3] now @s2[2] Mins starting at @s2[1] with $settings{'startbuffer'}, $settings{'endbuffer'} buffering\n");
											$timer_adjustments++;
										}
									} else {
										if( $show2start <= $show1start && $show2start < $tuner2start ){
											if( $show1start <= $tuner2start ){
												&adjustDuration($j,$settings{'endbuffer'});
												&adjustStart($i,$settings{'startbuffer'});
												@show1 = split(/\t/, @found[$i]);
												@show2 = split(/\t/, @found[$j]);
												my @s1 = split(/\t/, @found[$i]);	# Store the current show
												my @s2 = split(/\t/, @found[$j]);	# Store the current show
												&printOut("\t\t@s1[3] now @s1[2] Mins starting at @s1[1] with $settings{'startbuffer'}, $settings{'endbuffer'} buffering\n");
												&printOut("\t\t@s2[3] now @s2[2] Mins starting at @s2[1] with $settings{'startbuffer'}, $settings{'endbuffer'} buffering\n");
												$timer_adjustments++;
											} else {
												&adjustDuration($j,$settings{'endbuffer'});
												&adjustStart($tuner2showpointer,$settings{'startbuffer'});
												$tuner2start = &createStartTime(@found[$tuner2showpointer]); # Create the starting time
												$tuner2end = &createEndTime(@found[$tuner2showpointer]);	# Create ending string.
												@show2 = split(/\t/, @found[$j]);
												my @s1 = split(/\t/, @found[$tuner2showpointer]);	# Store the current show
												my @s2 = split(/\t/, @found[$j]);	# Store the current show
												&printOut("\t\t@s1[3] now @s1[2] Mins starting at @s1[1] with $settings{'startbuffer'}, $settings{'endbuffer'} buffering\n");
												&printOut("\t\t@s2[3] now @s2[2] Mins starting at @s2[1] with $settings{'startbuffer'}, $settings{'endbuffer'} buffering\n");
												$timer_adjustments++;
											}
										} else {
											if( $tuner2start <= $show1start && $tuner2start <= $show2start ){
												# Lets get the next shows start time
												if( $show1start <= $show2start ){
													&adjustDuration($tuner2showpointer,$settings{'endbuffer'});
													&adjustStart($i,$settings{'startbuffer'});
													@show1 = split(/\t/, @found[$i]);
													$tuner2start = &createStartTime(@found[$tuner2showpointer]); # Create the starting time
													$tuner2end = &createEndTime(@found[$tuner2showpointer]);	# Create ending string.
													my @s1 = split(/\t/, @found[$i]);	# Store the current show
													my @s2 = split(/\t/, @found[$tuner2showpointer]);	# Store the current show
													&printOut("\t\t@s2[3] now @s2[2] Mins starting at @s2[1] with $settings{'startbuffer'}, $settings{'endbuffer'} buffering\n");
													&printOut("\t\t@s1[3] now @s1[2] Mins starting at @s1[1] with $settings{'startbuffer'}, $settings{'endbuffer'} buffering\n");
													$timer_adjustments++;
												} else {
													&adjustDuration($tuner2showpointer,$settings{'endbuffer'});
													&adjustStart($j,$settings{'startbuffer'});
													@show2 = split(/\t/, @found[$j]);
													$tuner2start = &createStartTime(@found[$tuner2showpointer]); # Create the starting time
													$tuner2end = &createEndTime(@found[$tuner2showpointer]);	# Create ending string.
													my @s1 = split(/\t/, @found[$j]);	# Store the current show
													my @s2 = split(/\t/, @found[$tuner2showpointer]);	# Store the current show
													&printOut("\t\t@s2[3] now @s2[2] Mins starting at @s2[1] with $settings{'startbuffer'}, $settings{'endbuffer'} buffering\n");
													&printOut("\t\t@s1[3] now @s1[2] Mins starting at @s1[1] with $settings{'startbuffer'}, $settings{'endbuffer'} buffering\n");
													$timer_adjustments++;
												}
											}
										}
									}
									$j = @found;
									$i = -1;	# Reset the search to first element
#									$tuner2adjust = 0;
									next;
								# Attempt to resolve conflicts
								} elsif( @show1[9] && @show2[9] ){
									&printOut("\n\t@show1[3] and @show2[3] Adjustable\n\n");
									#	[ Show 1 ]
									#   [..[ Show 2 ]
									if( $show1start <= $show2start && $show1end >= $show2start ){
										print "\t\tAdjusting @show1[3] Duration from @show1[2]" if $debug;
										&adjustDuration($i,$settings{'endbuffer'});
										@show1 = split(/\t/, @found[$i]);
										&adjustStart($j,$settings{'startbuffer'});
										my @s1 = split(/\t/, @found[$i]);	# Store the current show
										my @s2 = split(/\t/, @found[$j]);	# Store the current show
										&printOut("\t\t@s1[3] now @s1[2] Mins starting at @s1[1] with $settings{'startbuffer'}, $settings{'endbuffer'} buffering\n");
										&printOut("\t\t@s2[3] now @s2[2] Mins starting at @s2[1] with $settings{'startbuffer'}, $settings{'endbuffer'} buffering\n");
										$timer_adjustments++;
									}
									#	[ Show 2 ]
									#           [ Show 1 ]
									elsif( $show2start <=$show1start && $show2end >= $show1start ){
										&adjustDuration($j,$settings{'endbuffer'});
										@show1 = split(/\t/, @found[$i]);
										&adjustStart($i,$settings{'startbuffer'});
										my @s1 = split(/\t/, @found[$i]);	# Store the current show
										my @s2 = split(/\t/, @found[$j]);	# Store the current show
										&printOut("\t\t@s1[3] now @s1[2] Mins starting at @s1[1] with $settings{'startbuffer'}, $settings{'endbuffer'} buffering\n");
										&printOut("\t\t@s2[3] now @s2[2] Mins starting at @s2[1] with $settings{'startbuffer'}, $settings{'endbuffer'} buffering\n");
										$timer_adjustments++;
									}
#									@show1 = split(/\t/, @found[$i]);
#									@show2 = split(/\t/, @found[$j]);
#									@show1[9] = 0;
#									@show2[9] = 0;
#									@found[$i] = join("\t",@show1);
#									@found[$j] = join("\t",@show2);
									$j = @found;
									$i = -1;	# Reset the search to first element
#									$tuner2adjust = 0;
									next;
								} elsif( @show1[9] && $tuner2adjust ){
									&printOut("\n\t@show1[3] and $tuner2show Adjustable\n\n");
									#	[ Show 1 ]
									#           [ Tuner2 ]
									if( $show1start <= $tuner2start && $show1end >= $tuner2start ){
										print "\t\tAdjusting @show1[3] Duration from @show1[2]" if $debug;
										&adjustDuration($i,$settings{'endbuffer'});
										@show1 = split(/\t/, @found[$i]);
										print " to @show1[2] by subtracting $settings{'endbuffer'} now ends at ".&createEndTime(@found[$j])."\n" if $debug;
										print "\t\tAdjusting $tuner2show\'s Start time from $tuner2start" if $debug;
										&adjustStart($tuner2showpointer,$settings{'startbuffer'});
										$tuner2start = &createStartTime(@found[$tuner2showpointer]); # Create the starting time
										print " to $tuner2start by adding 2 * $settings{'startbuffer'} to start time\n\n\n" if $debug;
										my @s1 = split(/\t/, @found[$i]);	# Store the current show
										my @s2 = split(/\t/, @found[$tuner2showpointer]);	# Store the current show
										&printOut("\t\t@s1[3] now @s1[2] Mins starting at @s1[1] with $settings{'startbuffer'}, $settings{'endbuffer'} buffering\n");
										&printOut("\t\t@s2[3] now @s2[2] Mins starting at @s2[1] with $settings{'startbuffer'}, $settings{'endbuffer'} buffering\n");
										$timer_adjustments++;
									}
									#	[ Tuner 2 ]
									#           [ Show 1 ]
									elsif( $tuner2start <= $show1start && $tuner2end >= $show1start ){
										print "\t\tAdjusting @show1[3] Duration from @show1[2]" if $debug;
										&adjustDuration($tuner2showpointer,$settings{'endbuffer'});
										@show1 = split(/\t/, @found[$i]);
										print " to @show1[2] by subtracting $settings{'endbuffer'} now ends at ".&createEndTime(@found[$j])."\n" if $debug;
										print "\t\tAdjusting $tuner2show\'s Start time from $tuner2start" if $debug;
										&adjustStart($i,$settings{'startbuffer'});
										$tuner2start = &createStartTime(@found[$tuner2showpointer]); # Create the starting time
										print " to $tuner2start by adding 2 * $settings{'startbuffer'} to start time\n\n\n" if $debug;
										my @s1 = split(/\t/, @found[$i]);	# Store the current show
										my @s2 = split(/\t/, @found[$tuner2showpointer]);	# Store the current show
										&printOut("\t\t@s1[3] now @s1[2] Mins starting at @s1[1] with $settings{'startbuffer'}, $settings{'endbuffer'} buffering\n");
										&printOut("\t\t@s2[3] now @s2[2] Mins starting at @s2[1] with $settings{'startbuffer'}, $settings{'endbuffer'} buffering\n");
										$timer_adjustments++;
									}
									$tuner2start = &createStartTime(@found[$tuner2showpointer]); # Create the starting time
									$tuner2end = &createEndTime(@found[$tuner2showpointer]);	# Create ending string.
#									@show1 = split(/\t/, @found[$i]);
#									@show2 = split(/\t/, @found[$j]);
#									@show1[9] = 0;
#									@show2[9] = 0;
#									@found[$i] = join("\t",@show1);
#									@found[$j] = join("\t",@show2);
									$j = @found;
									$i = -1;	# Reset the search to first element
#									$tuner2adjust = 0;
									next;
								} elsif( $tuner2adjust && @show2[9] ){
									&printOut("\n\t$tuner2show and @show2[3] Adjustable\n\n");
									#	[ Show 2 ]
									#           [ Tuner2 ]
									if( $show2start <= $tuner2start && $show2end >= $tuner2start ){
										print "\t\tAdjusting @show2[3] Duration from @show2[2]" if $debug;
										&adjustDuration($j,$settings{'endbuffer'});
										@show2 = split(/\t/, @found[$j]);
										print " to @show2[2] by subtracting $settings{'endbuffer'} now ends at ".&createEndTime(@found[$j])."\n" if $debug;
										print "\t\tAdjusting $tuner2show\'s Start time from $tuner2start" if $debug;
										&adjustStart($tuner2showpointer,$settings{'startbuffer'});
										$tuner2start = &createStartTime(@found[$tuner2showpointer]); # Create the starting time
										print " to $tuner2start by adding 2 * $settings{'startbuffer'} to start time\n\n\n" if $debug;
										my @s1 = split(/\t/, @found[$j]);	# Store the current show
										my @s2 = split(/\t/, @found[$tuner2showpointer]);	# Store the current show
										&printOut("\t\t@s1[3] now @s1[2] Mins starting at @s1[1] with $settings{'startbuffer'}, $settings{'endbuffer'} buffering\n");
										&printOut("\t\t@s2[3] now @s2[2] Mins starting at @s2[1] with $settings{'startbuffer'}, $settings{'endbuffer'} buffering\n");
										$timer_adjustments++;
									}
									#	[ Tuner 2 ]
									#           [ Show 2 ]
									elsif( $tuner2start <= $show2start && $tuner2end >= $show2start ){
										print "\t\tAdjusting @show2[3] Duration from @show2[2]" if $debug;
										&adjustDuration($tuner2showpointer,$settings{'endbuffer'});
										@show2 = split(/\t/, @found[$j]);
										print " to @show2[2] by subtracting $settings{'endbuffer'} now ends at ".&createEndTime(@found[$j])."\n" if $debug;
										print "\t\tAdjusting $tuner2show\'s Start time from $tuner2start" if $debug;
										&adjustStart($j,$settings{'startbuffer'});
										$tuner2start = &createStartTime(@found[$tuner2showpointer]); # Create the starting time
										print " to $tuner2start by adding 2 * $settings{'startbuffer'} to start time\n\n\n" if $debug;
										my @s1 = split(/\t/, @found[$j]);	# Store the current show
										my @s2 = split(/\t/, @found[$tuner2showpointer]);	# Store the current show
										&printOut("\t\t@s1[3] now @s1[2] Mins starting at @s1[1] with $settings{'startbuffer'}, $settings{'endbuffer'} buffering\n");
										&printOut("\t\t@s2[3] now @s2[2] Mins starting at @s2[1] with $settings{'startbuffer'}, $settings{'endbuffer'} buffering\n");
										$timer_adjustments++;
									}
									$tuner2start = &createStartTime(@found[$tuner2showpointer]); # Create the starting time
									$tuner2end = &createEndTime(@found[$tuner2showpointer]);	# Create ending string.
#									$tuner2adjust = 0;
#									@show1 = split(/\t/, @found[$i]);
#									@show2 = split(/\t/, @found[$j]);
#									@show1[9] = 0;
#									@show2[9] = 0;
#									@found[$i] = join("\t",@show1);
#									@found[$j] = join("\t",@show2);
									$j = @found;
									$i = -1;	# Reset the search to first element
									# Start loop again and hope we have fixed conflict. This should bypass next loop
									next;
								} elsif( @show1[9] ){
									print "\t\tShow1 Adjustable" if $debug;
									if( !(( $show1start <= $show2start ) && ( $show1end >= $show2end ))){
										&printOut("\n\t@show1[3] Adjustable\n");
										# [ Tuner 2 Show ]
										#         [ Show 1 ]
										#         [ Show 2 ]
										if( $show1start <= $show2end 
										 && $show1end <= $show2end
										 && $show1end >= $show2start ){
										 	# Now the show overlaps at the start. Lets determine whether the en d is also effected
											#     [ Tuner 2 Show ]
											# [ Show 1 ]       [ Show 1 ]
											# [ Show 2 ]       [ Show 2 ]
											if( $show1start >= $show2start 
											 && $show1end >= $show2end
											 && $show1start <= $show2end ){
											 	# Overlap front and back. We need to alter both duration and start
												my $av = 0;
												$av = -$settings{'startbuffer'};
												$av -= (-$settings{'endbuffer'}+$settings{'startbuffer'});
												&adjustStart($i,$settings{'startbuffer'});
												&adjustStartTime($i,-$settings{'endbuffer'}+$settings{'startbuffer'}-1);
												&adjustDuration($i,$av);
												$timer_adjustments++;											 
											} else {
												my $av = 0;
												$av -= (-$settings{'endbuffer'}+$settings{'startbuffer'});
												&adjustDuration($i,$av);
												$timer_adjustments++;
											}
										} else {
											#     [ Tuner 2 Show ]
											# [ Show 1 ]
											# [ Show 2 ]
											if( $show1start <= $show2end 
											 && $show1end >= $show2end
											 && $show2end >= $show1start ){
											 	# Now the show overlaps at the start. Lets determine whether the en d is also effected
												#     [ Tuner 2 Show ]
												# [ Show 1 ]       [ Show 1 ]
												# [ Show 2 ]       [ Show 2 ]
												if( $show1start >= $show2start 
												 && $show1end >= $show2end
												 && $show1start <= $show2end ){
												 	# Overlap front and back. We need to alter both duration and start
													my $av = 0;
													$av = -$settings{'startbuffer'};
													$av -= (-$settings{'endbuffer'}+$settings{'startbuffer'});
													&adjustStart($i,$settings{'startbuffer'});
													&adjustStartTime($i,-$settings{'endbuffer'}+$settings{'startbuffer'}-1);
													&adjustDuration($i,$av);
													$timer_adjustments++;											 
												} else {
													&printOut("Front Overlap\n");
													&adjustStart($i,$settings{'startbuffer'});
													$timer_adjustments++;
												}
											}
										}
										my @s1 = split(/\t/, @found[$i]);	# Store the current show
										&printOut("\n\t\t@s1[3] now @s1[2] Mins starting at @s1[1] with $settings{'startbuffer'}, $settings{'endbuffer'} buffering\n");
										@show1 = split(/\t/, @found[$i]);
										@show1[9] = 0;
										@found[$i] = join("\t",@show1);
										$j = @found;
										$i = -1;	# Reset the search to first element
										next;
									}
								} elsif( @show2[9] ){
									print "\t\tShow2 Adjustable" if $debug;
									if( !(( $show2start <= $show1start ) && ( $show2end >= $show1end ))){
										&printOut("\n\t@show2[3] Adjustable\n");
										# [ Tuner 2 Show ]
										#         [ Show 1 ]
										#         [ Show 2 ]
										if( $show2start <= $show1end 
										 && $show2end <= $show1end
										 && $show2end >= $show1start ){
										 	# Now the show overlaps at the start. Lets determine whether the en d is also effected
											#     [ Tuner 2 Show ]
											# [ Show 1 ]       [ Show 1 ]
											# [ Show 2 ]       [ Show 2 ]
											if( $show2start >= $show1start 
											 && $show2end >= $show1end
											 && $show2start <= $show1end ){
											 	# Overlap front and back. We need to alter both duration and start
												my $av = 0;
												$av = -$settings{'startbuffer'};
												$av -= (-$settings{'endbuffer'}+$settings{'startbuffer'});
												&adjustStart($j,$settings{'startbuffer'});
												&adjustStartTime($j,-$settings{'endbuffer'}+$settings{'startbuffer'}-1);
												&adjustDuration($j,$av);
												$timer_adjustments++;											 
											} else {
												my $av = 0;
												$av -= (-$settings{'endbuffer'}+$settings{'startbuffer'});
												&adjustDuration($j,$av);
												$timer_adjustments++;
											}
										} else {
											#     [ Tuner 2 Show ]
											# [ Show 1 ]
											# [ Show 2 ]
											if( $show2start <= $show1end 
											 && $show2end >= $show1end
											 && $show1end >= $show2start ){
											 	# Now the show overlaps at the start. Lets determine whether the en d is also effected
												#     [ Tuner 2 Show ]
												# [ Show 1 ]       [ Show 1 ]
												# [ Show 2 ]       [ Show 2 ]
												if( $show2start >= $show1start 
												 && $show2end >= $show1end
												 && $show2start <= $show1end ){
												 	# Overlap front and back. We need to alter both duration and start
													my $av = 0;
													$av = -$settings{'startbuffer'};
													$av -= (-$settings{'endbuffer'}+$settings{'startbuffer'});
													&adjustStart($j,$settings{'startbuffer'});
													&adjustStartTime($j,-$settings{'endbuffer'}+$settings{'startbuffer'}-1);
													&adjustDuration($j,$av);
													$timer_adjustments++;											 
												} else {
													&adjustStart($j,$settings{'startbuffer'});
													$timer_adjustments++;
												}
											}
										}
										@show2 = split(/\t/, @found[$j]);
										my @s1 = split(/\t/, @found[$j]);	# Store the current show
										&printOut("\n\t\t@s1[3] now @s1[2] Mins starting at @s1[1] with $settings{'startbuffer'}, $settings{'endbuffer'} buffering\n");
										@show2[9] = 0;
										@found[$j] = join("\t",@show2);
										$j = @found;
										$i = -1;	# Reset the search to first element
										next;
									}
								} elsif( $tuner2adjust ){
									print "\t\tTuner2 Adjustable" if $debug;
									if( !(( $tuner2start <= $show1start ) && ( $tuner2end >= $show1end ))){
										&printOut("\n\t$tuner2show Adjustable\n");
										# [ Tuner 2 Show ]
										#         [ Show 1 ]
										#         [ Show 2 ]
										if( $tuner2start <= $show1end 
										 && $tuner2end <= $show1end
										 && $tuner2end >= $show1start ){
										 	# Now the show overlaps at the start. Lets determine whether the en d is also effected
											#     [ Tuner 2 Show ]
											# [ Show 1 ]       [ Show 1 ]
											# [ Show 2 ]       [ Show 2 ]
											if( $tuner2start >= $show1start 
											 && $tuner2end >= $show1end
											 && $tuner2start <= $show1end ){
											 	# Overlap front and back. We need to alter both duration and start
												my $av = 0;
												$av = -$settings{'startbuffer'};
												$av -= (-$settings{'endbuffer'}+$settings{'startbuffer'});
												&adjustStart($tuner2showpointer,$settings{'startbuffer'});
												&adjustStartTime($tuner2showpointer,-$settings{'endbuffer'}+$settings{'startbuffer'}-1);
												&adjustDuration($tuner2showpointer,$av);
												$timer_adjustments++;											 
											} else {
												my $av = 0;
												$av -= (-$settings{'endbuffer'}+$settings{'startbuffer'});
												&adjustDuration($tuner2showpointer,$av);
												$timer_adjustments++;
											}
										} else {
											#     [ Tuner 2 Show ]
											# [ Show 1 ]
											# [ Show 2 ]
											if( $tuner2start <= $show1end 
											 && $tuner2end >= $show1end
											 && $show1end >= $tuner2start ){
											 	# Now the show overlaps at the start. Lets determine whether the en d is also effected
												#     [ Tuner 2 Show ]
												# [ Show 1 ]       [ Show 1 ]
												# [ Show 2 ]       [ Show 2 ]
												if( $tuner2start >= $show1start 
												 && $tuner2end >= $show1end
												 && $tuner2start <= $show1end ){
												 	# Overlap front and back. We need to alter both duration and start
													my $av = 0;
													$av = -$settings{'startbuffer'};
													$av -= (-$settings{'endbuffer'}+$settings{'startbuffer'});
													&adjustStart($tuner2showpointer,$settings{'startbuffer'});
													&adjustStartTime($tuner2showpointer,-$settings{'endbuffer'}+$settings{'startbuffer'}-1);
													&adjustDuration($tuner2showpointer,$av);
													$timer_adjustments++;											 
												} else {
													&adjustStart($tuner2showpointer,$settings{'startbuffer'});
													$timer_adjustments++;
												}
											}
										}
										my @s1 = split(/\t/, @found[$tuner2showpointer]);	# Store the current show
										&printOut("\n\t\t@s1[3] now @s1[2] Mins starting at @s1[1] with $settings{'startbuffer'}, $settings{'endbuffer'} buffering\n");
										$j = @found;
										$i = -1;	# Reset the search to first element
										$tuner2adjust = 0;
										$tuner2start = &createStartTime(@found[$tuner2showpointer]); # Create the starting time
										$tuner2end = &createEndTime(@found[$tuner2showpointer]);	# Create ending string.
										next;
									}
								}
								##
								##	Now to drop the conflicting shows
								##	We got here because all possible adjustments to the conflicts have been made
								##
								
								# Check to see whether to drop show 1
								if( $tuner2priority > @show1[8] ){
									if( @show1[8] > @show2[8] ){
										&printOut("\n\t@show2[3] currently selected dropped\n\n\t\tTuner 1        ::: @show1[3]\n\t\tTuner 2        ::: $tuner2show\n");
										splice(@found,$j,1);	# Remove the conflicting timer
										$j = @found;
										$i = $i-1;
										$timer_clashes++;
									} else {
										&printOut("\n\t@show1[3] currently on Tuner 1 dropped\n\n\t\tTuner 2        ::: $tuner2show\n\t\tThis Show      ::: @show2[3]\n");
										splice(@found,$i,1);	# Remove the conflicting timer
										$j = @found;
										$i = -1;	# Reset the search to first element
										$timer_clashes++;
									}
								}								
								# Lets check whether to drop show2
								elsif( $tuner2priority > @show2[8] ){
									if( @show2[8] > @show1[8] ){
										&printOut("\n\t@show1[3] currently on Tuner 1 dropped\n\n\t\tTuner 2        ::: $tuner2show\n\t\tThis Show      ::: @show2[3]\n");
										splice(@found,$i,1);	# Remove the conflicting timer
										$j = @found;
										$i = -1;	# Reset the search to first element
										$timer_clashes++;
									} else {
										&printOut("\n\t@show2[3] currently selected dropped\n\n\t\tTuner 1        ::: @show1[3]\n\t\tTuner 2        ::: $tuner2show\n");
										splice(@found,$j,1);	# Remove the conflicting timer
										$j = @found;
										$i = $i-1;
										$timer_clashes++;
									}
								} else {
									&printOut("\n\t$tuner2show currently on Tuner 2 dropped\n\n\t\tTuner 1        ::: @show1[3]\n\t\tThis Show      ::: @show2[3]\n");
									splice(@found,$tuner2showpointer,1);	# Remove the conflicting timer
									$j = @found;
									$i = -1;
									$timer_clashes++;
								}
							}
						} else {
							# No show on second tuner so add.
							# Store the values of the show on the tuner to check whether the show on tuner
							# clashes with both show 1 and show 2
							$tuner2show = @show2[3]; 
							$tuner2channel = @show2[0]; 
							$tuner2start = $show2start;
							$tuner2end = $show2end;
							$tuner2 = 1; 
							$tuner2priority = @show2[8];
							$tuner2showpointer = $j;
							$tuner2adjust = @show2[9];
						}
					}
				}
			}
		}
		# Reset tuner 2 variables. Make sure we are set back to default values
		$tuner2 = 0;
		$tuner2show = ""; 
		$tuner2channel = ""; 
		$tuner2start = 0;
		$tuner2end = 0;
		$tuner2priority = 0;
		$tuner2showpointer = 0;
		$tuner2adjust = 0;
	}
}


# function to create title string. Attempts to get the Show - Episode if not joined.
# Adds the date stamp to all the but show - episode titles
sub createTitle(){
	my $sent_show = shift @_;	# TGD String
	my @timerobj = split(/\t/, $sent_show);
	my $newtitle = @timerobj[3];

	# Generate the date stamp for time
	my $day = sprintf("%02d",substr( @timerobj[1], 8, 2 ));
	my $month = sprintf("%02d",substr( @timerobj[1], 5, 2 ));
	my $year = sprintf("%04d",substr( @timerobj[1], 0, 4 ));
	my $yearshrt = sprintf("%02d",substr( @timerobj[1], 2, 2 ));

	my $stamp = $settings{'datestamp'};

	$stamp =~ s/DD/$day/ig;
	$stamp =~ s/MM/$month/ig;
	$stamp =~ s/YYYY/$year/ig;
	$stamp =~ s/YY/$yearshrt/ig;
	
	if( @timerobj[4] !~ /Joined TGD/ ){ 	# If show hasn't been joined then attempt to put sub title in title
		if( @timerobj[4] =~ /\[/ ){	# If subtitle contains [ for [comedy] see if there is a title before
			my @subtitle = split(/\[/, @timerobj[4]);
			if( @subtitle[0] =~ /['a' .. 'z']/ and @subtitle[0] !~ /\]/ and @subtitle[0] !~ /^ /){	# Subtitle somewhere contains a character i.e not " ".
				$newtitle = "@timerobj[3]$settings{'showtitle'}@subtitle[0]";
				if( length($newtitle) > 44 && !length($newtitle) > 48 ){
					my $cuttitle =	substr($newtitle,0,44); 
					$newtitle = "$cuttitle";
				}
				$newtitle =~ s/\.//ig;
			} else {
				if( length($newtitle) > 40 ){
					my $cuttitle =	substr($newtitle,0,40);
					$newtitle = "$cuttitle .. $stamp";
				} else { $newtitle = "$newtitle $stamp"; }				
			}
		} else {
			if( length($newtitle) > 40 ){
				my $cuttitle =	substr($newtitle,0,40); 
				$newtitle = "$cuttitle .. $stamp";
			} else { $newtitle = "$newtitle $stamp"; }
		}
	} else {
		if( length($newtitle) > 40 ){	# Only Allow 40 chars with date stamp appended
			my $cuttitle =	substr($newtitle,0,40); 
			$newtitle = "$cuttitle .. $stamp";
		} else {
			$newtitle = "$newtitle $stamp";
		}
	}
	return &trim($newtitle);
}

# function to create title string Show - Episode
sub createName(){
	my $sent_show = shift @_;	# TGD String
	my @timerobj = split(/\t/, $sent_show);
	my $newtitle = @timerobj[3];
	if( @timerobj[4] =~ /\[/ ){	# If subtitle contains [ for [comedy] see if there is a title before
		my @subtitle = split(/\[/, @timerobj[4]);
		if( @subtitle[0] =~ /['a' .. 'z']/ and @subtitle[0] !~ /\]/ and @subtitle[0] !~ /^ /){	# Subtitle somewhere contains a character i.e not " ".
			$newtitle = "@timerobj[3]$settings{'showtitle'}@subtitle[0]";
			$newtitle =~ s/\.//ig;
		}
	}
	return &trim($newtitle);
}

# function to create title string Show - Episode
sub createDate(){
	my @show = split(/\t/, shift @_);
	my $year = sprintf('%04d',substr(@show[1],0,4));
	my $month = sprintf('%02d',substr(@show[1],5,2));
	my $day = sprintf('%02d',substr(@show[1],8,2));
	return "$year$month$day";
}

#####################################################################################
#                                     Utilities                                     #
#####################################################################################

# Copied from DayOfWeek perl modules
sub dayOfWeek() { # calculate the day-of-the-week from the Year, Month, and Day
  my $year = shift; $year = 2000 unless(defined($year));
  my $mont = shift; $mont =    1 unless(defined($mont) && $mont);  # 1..12
  my $daay = shift; $daay =    1 unless(defined($daay) && $daay);  # 1..31
  my $mndx = int((14 - $mont) / 12); 
  my $yshf = $year - $mndx; my $ys4h = $yshf / 400; 
  my $tmp;
  $daay += $yshf + int($ys4h) - int($ys4h * 4) + int($ys4h * 100);
  $tmp = (($daay + (31 * int((12 * $mndx) + $mont - 2)) / 12) % 7);
  if((($year%4==0) and ($year%400==0 or $year%100!=0)) || 0){
  	if( $mont > 2 ){	# Must be after february to add a day to take into account the leap year
	  	$tmp++;
  		$tmp = $tmp%7;
  	}
  }
  return($tmp);
}


# function to check the connection with the topfield and loop 5 times with a 30 second delay
sub toppyConnected(){
	&printOut("    Checking Toppy Connection\n\n");
	for( 1 .. 5 ){
		if( &isToppyConnected() ){
			&printOut("        Toppy Connected\n");
			return 1;
		} else {
			&printOut("        Toppy Not Connected - Please Connect Unit. Will retry in 30 Seconds\n");
			sleep 20;
		}
	}
	return 0;
	&printOut("    Toppy Not Connected. Tansfer will abort\n");
}

# function to check whether we are recording atm
# Since i dont know how other apps reboot the topfield i can't support them.
sub isRecording(){
	my $download_string = $settings{'download'};
	$download_string =~ s/<CURRENT>/$settings{'workdir'}/ig;
	$download_string =~ s/<TGD>/$settings{'tgddir'}/ig;
	$download_string =~ s/<OUTPUT>/$settings{'outputdir'}/ig;
	$download_string =~ s/<FILE>/$recplay/ig;
	$download_string =~ s/<TFDIR>/$settings{'tfdir'}/ig;
	# Download the file from the unit
	`$download_string`;
	my $returnvalue = 0;
	# Lets open this file and read the contents
	if( -e "$settings{'outputdir'}/$recplay" and -r "$settings{'outputdir'}/$recplay" ){
		open( FILE, "$settings{'outputdir'}/$recplay" );
		while( <FILE> ){
			chomp;
			my @status = split( "\t", $_ );
			if( &trim(@status[1]) ){
				$returnvalue = 1;
			}
		}
	}
	return $returnvalue;
}

# function to check that the topfield PVR is connected. Need to work out if MAC is the same
sub isToppyConnected(){
	if( `which lsusb` ){	# Make sure lsusb is present otherwise just continue
		my $usb = `lsusb`;
		if( $usb =~ /Topfield/g ){
			return 1;
		} else {
			return 0;
		}
	}
	return 1;
}

# function to generate the TGD Sting from the epg_timers.tsv format
sub buildTGDStringFromEPGTimers(){
	my $str = shift @_;
	my @tsv = split( /\t/, $str );
	if( @tsv < 10 ){ return undef; }	# Not a valid number of elements in the string
	my $timer_name = &trim(@tsv[0]);
	$timer_name =~ s/\.rec//i;
	if( !exists $channelHash{&trim(@tsv[11])} ){
		$channel = &trim(@tsv[11]);
	} else {
		$channel = $channelHash{&trim(@tsv[11])};
	}
	my $datetime = &buildDateTimeFromEPGTimers(@tsv[3]);
	my $duration = @tsv[4];
	return "$channel\t$datetime\t$duration\t$timer_name";
}

# funtion to convert the epg_timers time format to TGD Standard
sub buildDateTimeFromEPGTimers(){
	my $st = shift @_;
	( my $dt, my $t ) = split( / /, $st );
	return substr( $dt, 0, 4 )."-".substr( $dt, 4, 2 )."-".substr( $dt, 6, 2 )." $t";
}

# function to create the date time string with repect to the start buffer
sub createDateTime(){
	my $sv = shift @_;
	my @temp = split(/ /, $sv);	# Split Up Date
	my @date = split(/-/,@temp[0]);	# Extract day from string dd hh:mm
	my @time = split(/:/,@temp[1]);	# 0 = Hour 1 = Minutes
	my $minutes = (@time[0]*60+@time[1]) + $settings{'startbuffer'};
	# Check that show doesn't now start the day before
	if( $minutes < 0 ){
		# Dang. the show starts on the previous day. Lets change
		$minutes = 1440 + $minutes;	# This will be a negative number so no use. 1440 is minutes in a day so add
		@date = &subtractDay(@date[0], @date[1], @date[2],1);
	}
	$minutes = sprintf('%04d',$minutes);
	my $year = sprintf('%04d',$date[0]);
	my $month = sprintf('%02d',$date[1]);
	my $day = sprintf('%02d',$date[2]);
	
	# Convert time back to HH:MM Format
	my $mins = $minutes % 60;
	my $hour = ($minutes - $mins) / 60;
	# Return the calculated value
	return "$year-$month-$day ".sprintf('%02d',$hour).":".sprintf('%02d',$mins);
}

sub isLeapYear() {
    my $y = shift;
    return (($y%4==0) and ($y%400==0 or $y%100!=0)) || 0;
}

sub subtractDay(){
	my $year = shift @_;
	my $month = shift @_;
	my $date = shift @_;
	my $dta = shift @_;
	if( !$dta ){ $dta = 1; }# Number of days to add
	my @days_in_month = (
	 [0,31,28,31,30,31,30,31,31,30,31,30,31],
	 [0,31,29,31,30,31,30,31,31,30,31,30,31],
	);
	$date -= $dta;
	if( $date < 1 ){	# Previous Month
		$month--;
		if( $month < 1 ){
			$year--;
			$month = 12;
		}
		$date = $days_in_month[&isLeapYear($year)][$month] + $date;	
	}
	return ($year,$month,$date);
}

sub addDay(){
	my $year = shift;
	my $month = shift;
	my $date = shift;
	my $dta = shift;
	if( !$dta ){ $dta = 1; }# Number of days to add
	my @days_in_month = (
	 [0,31,28,31,30,31,30,31,31,30,31,30,31],
	 [0,31,29,31,30,31,30,31,31,30,31,30,31],
	);
	$date += $dta;
	if( $date > $days_in_month[&isLeapYear($year)][$month]){
		$date = $date - $days_in_month[&isLeapYear($year)][$month];
		$month++;
	}
	if( $month > 12 ){
		$month = 1;
		$year++;
	}
	return ($year,$month, $date);
}

# function that creates starttime variable of format YYYYMMDDMMMM(Minutes) for comparison
sub createStartTime(){
	my @show = split(/\t/, shift @_);
	my @temp = split(/ /,@show[1]);	# Split Up Date
	my @date = split(/-/,@temp[0]);	# Extract day from string dd hh:mm
	my @time = split(/:/,@temp[1]);	# 0 = Hour 1 = Minutes
	my $starting_time = (@time[0]*60+@time[1]) + $settings{'startbuffer'};
	# Check that show doesn't now start the day before
	if( $starting_time < 0 ){
		$starting_time = 1440 + $starting_time;	# This will be a negative number so no use. 1440 is minutes in a day so add
		@date = &subtractDay(@date[0], @date[1], @date[2],1);
	}
	return (sprintf('%04d',$date[0]).sprintf('%02d',$date[1]).sprintf('%02d',$date[2]).sprintf('%04d',$starting_time));
}

# function that creates endtime variable of format YYYYMMDDMMMM(Minutes) for comparison
sub createEndTime(){
	my @show = split(/\t/, shift @_);
	my @temp = split(/ /,@show[1]);	# Split Up Date
	my @date = split(/-/,@temp[0]);	# Extract day from string dd hh:mm
	my @time = split(/:/,@temp[1]);	# 0 = Hour 1 = Minutes
	my $ending_time = (@time[0]*60+@time[1]) + @show[2] + $settings{'endbuffer'};
	if( $ending_time > 1439 ){ 
		$ending_time = $ending_time - 1440; 
		@date = &addDay(@date[0], @date[1], @date[2],1);
	}
	return (sprintf('%04d',$date[0]).sprintf('%02d',$date[1]).sprintf('%02d',$date[2]).sprintf('%04d',$ending_time));
}

# function to check whether the show is shit
sub isShowOverrun(){
	my $tgd = shift @_;
	my @tgdobj = split(/\t/, $tgd);
	if( $channel ){
		if( $channel !~ @tgdobj[0] ){
			&printOut("\t\t\tResetting Overrun Detection\n");
			# If we are not the same channel the reset the variables
			$overrun_show = 0;
			$channel = "";
		}
	}
	if( $overrun_show ){
		return;
	}
	foreach my $show ( @overrun_shows ){
		if( $tgdobj[3] =~ /$show/ig ){
			# Show is shit so set the variables for channel and status
			$channel = $tgdobj[0];
			$overrun_show = 1;
			&printOut("\t\t\t".substr(@tgdobj[3],0,25)."... detected. Flagging for overrun\n");
			return;
		}
	}
}

# function to return the number of minutes from a favourite item
# Handles HH:MM, -1, Any or 1209 formats
sub fav2Minutes(){
	my $time = shift @_;
	if( $time =~ /\:/g ){
		(my $hr, my $min) = split(/\:/, $time );
		return ($hr*60) + $min;
	} else {
		if( $time =~ /Any/i ){
			return -1;
		} else {
			return $time;	# Dont touch as numbers in miountes already
		}
	}
}

# function to get the show start time in minutes for favourites time check
sub showStartMinutes(){
	my $showstart = shift @_;
	( my $drop, my $needed ) = split / /, $showstart;	# $drop should contain date YYYY-MM-DD $needed HH:MM
	my @start = split /:/, $needed;
	return (@start[0]*60 + @start[1]);
}

# function that checks the event is in the correct time frame of the favourite element.
sub timeCheck(){
	my $favstart = &fav2Minutes(shift @_);
	my $favend = &fav2Minutes(shift @_);
	my $showstart = &showStartMinutes(shift @_);
	if( $favstart =~ -1 && $favend =~ -1 ){ 
		return 1; 
	}	# If there is no contrains on fav then return
	if( $favstart !~ -1 && $favend =~ -1 ){ 
		if( $showstart >= $favstart ){ 
			return 1; 
		}
	}	# Show has to start after fav start time
	if( $favstart =~ -1 && $favend !~ -1 ){ 
		if( $showstart <= $favend ){
			return 1;
		}
	}	# Show has to start before fav end time
	if( $favstart !~ -1 && $favend !~ -1 ){ 
		if( $showstart >= $favstart && $showstart <= $favend ){ 
			return 1; 
		}
	} 	# Has to start between these times
	return 0;
}

#####################################################################################
#                                 Output to Terminal                                #
#####################################################################################

# function to print the finishing output
sub finish(){
	# Get the end time for completion
	@time_counter = localtime(time);
	my $time_ended = (@time_counter[0] + (@time_counter[1]*60) + (@time_counter[2]*60*60));
	# Calculate the total time taken
	my $time_taken = $time_ended - $time_started;
	&printOut("\tTotal Time Taken ::: $time_taken secs\n\n");
	&writeLogFile();	# Write the log file out
	exit;
}

sub searchLog(){
	my $afterjoin = $no_found-($no_found-@found);	# Get number of shows after joining and clash detection
	&printOut("\n    Results Of Search\n\n");
	&printOut("\t\tNumber of shows found      ::: $no_found\n");
	&printOut("\t\tNumber of repeats omitted  ::: $no_repeats\n");
	&printOut("\t\tNumber shows after joining ::: $afterjoin\n");
	&printOut("\t\tAdjustments made           ::: $timer_adjustments\n");
	&printOut("\t\tNumber of timer clashes    ::: $timer_clashes\n");
	&printOut("\n\t\t\t\t\tFrom $events events\n");
}

# function to print the shows full timer string to be used. Testing
sub outputTimersScreen(){
	@found = sort(@found);
	if( @found ){
		&printOut("\n    Timers To Be Set\n\n\t   Date/Time   \t    Duration\tTitle\n\n");
		for( my $i = 0; $i<@found; $i++ ){
			my @timerobj = split(/\t/, @found[$i]);
			my $timer_title = &createTitle(@found[$i]);
			&printOut("\t@timerobj[1]\t@timerobj[2]\t$timer_title\n");
		}
	}
}

sub writeLogFile(){
	if( $settings{'writelog'} =~ /yes/i ){
		if( -e "$settings{'workdir'}/$log_file" ){
			open (LOG, ">>$settings{'workdir'}/$log_file");
			seek(LOG, 0, 2); # Seek to the end of the file
			print LOG $log_string;
			close LOG;
		} else {
			open (LOG, ">$settings{'workdir'}/$log_file");
			seek(LOG, 0, 2); # Seek to the end of the file
			print LOG $log_string;
			close LOG;
		}
	}
}

# Sub routine to create lcn hash full of tgd channel names
sub createChannelHash(){
	my $input = shift @_;
	my @rename = split(/:/,$input);
	foreach( @rename ){
		( my $lcn, my $name ) = split( /-/ );
		$channelHash{$lcn} = $name;
	}
}

# function to write the log to file
sub printOut(){
	my $temp = shift @_;
	$log_string .= $temp;
	print $temp;
}

# function that prints out the settings in the hash
sub printSettings(){
	&printOut("\n                          perlTGD Version $version\n");
	my $now_start = localtime(time);
	&printOut("\n                          $now_start\n\n");
	&printOut(   "        Working Directory       :  $settings{'workdir'}\n");
	&printOut( "        Output Directory        :  $settings{'outputdir'}\n");
	&printOut(     "        Topfield Directory      :  $settings{'tfdir'}\n");
	&printOut("        Repeat Flag             :  $settings{'repeatflag'}\n");
	&printOut( "        Repeat Method           :  $settings{'repeatmethod'}\n");
	&printOut(   "        Favourites File         :  $settings{'favfile'}\n");
	&printOut( "        Date Stamp              :  $settings{'datestamp'}\n");
	&printOut("        Start Buffer            :  $settings{'startbuffer'}\n");
	&printOut( "        End Buffer              :  $settings{'endbuffer'}\n");
	&printOut(      "        Join Delimeter          :  $settings{'join'}\n");
	&printOut( "        Title Episode Delimeter :  $settings{'showtitle'}\n");
	&printOut(   "        Download Call           :  $settings{'grabber'}\n");
	&printOut(   "        Download Favourites     :  $settings{'downloadfav'}\n");
	&printOut( "        Make Guide Call         :  $settings{'makeguide'}\n");
	&printOut( "        Time to Add For Overrun :  $settings{'overrun'} mins\n");
	&printOut(   "        Additional Time         :  $settings{'addtime'} mins\n");
	&printOut("        Additional Time Start   :  $settings{'addtimestart'}\n");
	&printOut("        Additional Time End     :  $settings{'addtimeend'}\n");
	&printOut(  "        Download String         :  $settings{'download'}\n");
	&printOut(  "        Transfer String         :  $settings{'transfer'}\n");
	&printOut(  "        UK Favourites Download  :  $settings{'ukfavfile'}\n");
	&printOut(  "        Ignore timers           :  $settings{'ignoretimers'}\n\n");
	&printOut(    "        Reboot String           :  $settings{'reboot'}\n");
	&printOut(   "        LCN - TGD channel names :  $settings{'lcnname'}\n");
	&printOut(  "        Write Log File          :  $settings{'writelog'}\n\n");
	&printOut("        Actions to be performed\n\n");
	&printOut("            Download EPG            :  ");
	$download_epg?&printOut("Yes\n"):&printOut("No\n");
	&printOut("            Make TGD Documents      :  ");
	$make_tgd?&printOut("Yes\n"):&printOut("No\n");
	&printOut("            Search EPG              :  ");
	$search_epg?&printOut("Yes\n"):&printOut("No\n");
	&printOut("            Output Timers           :  ");
	$output_timers?&printOut("Yes\n"):&printOut("No\n");
	&printOut("            Transfer EPG            :  ");
	$transfer_epg?&printOut("Yes\n"):&printOut("No\n");
	&printOut("            Reboot Unit             :  ");
	$reboot_toppy?&printOut("Yes\n"):&printOut("No\n");
	&printOut("\n");
}

