#!/tvbin/tivosh 

# dailymail_jazz.tcl
# email TiVo status and info
#
# Original Baseline Version 0.3 (29/11/03) by Stuart Anderton (sanderton at tivocommunity.com)
# Some procs borrowed from TiVoWeb as you can't call them by reference
# Just jazzed up a little by Chris Stennett (tivo-onion at tivocommunity.com)
#
# Change Log:
# -----------
#	01 Oct 05 ---- v1.0-----------------------
#	- First Formal Release
#	02 May 06 ---- v1.01-----------------------
#	- fixes included that have been explained in the TiVo Community Forums
#       - up to this date.
#
#
# VERSION INFORMATION SET HERE:
set software_version "1.01"
set software_release_date "02 May 2006"
#
#
#

# error stack global variable for error handling
global errorInfo

###########################################################################################################
## MAIN CODE

## initial logging text
puts ""
puts ""
puts "------welcome to the jazzed dailymail program - v$software_version ($software_release_date) - starting"

## variable to specify whether the memory cataloging function should run at the end of the module.
set memcat false

## some default setup variables for earlier version code users - will be overriden by config file if current version used
set externalipsetting false
set oursiteport ""
set oursitevirtualpath ""
set oursitesecure false
set externalsiteip ""
set externalsitestartmap ""
set externalsiteendmap ""
set externallogging false
set sortnowshowing ""
set nowshowingrepeatfreq 15
set multicolourbar false
set sortnowshowingascdesc "ASC"
set nowshowingdaylimit 0

## setup alert option variables
set alertstatus false
set alertreasons ""

## attach configuration file
set pathname [file dirname [info script]]
source $pathname/dailymail.cfg

## attach ip utilities script
catch {	source $pathname/ip-utilities.tcl }
catch { unset pathname }

## logging text regarding language and start time
puts "------the debug level is set at >>$debuglvl<<"
if {$yankspeak} { puts "------generated content presented in American English for your reading pleasure!" }
puts "------started at [clock format [clock seconds] -format {%H:%M:%S} -gmt true] (debugging times specified in gmt)"
puts ""

## validate that pool size is large enough to run script - else cop out
if {[pool pool0 size] <= 1622016} {
	puts "Use the 'dailymail_jazz' script to start the dailymail_jazz module!"
	puts ""
	puts "------completed the jazzed dailymail program - v$software_version ($software_release_date) - thanks for your custom"
	puts "------completed at [clock format [clock seconds] -format {%H:%M:%S} -gmt true]"
	puts ""
	puts ""
	exit
}

## setup ip information
catch {
	if {$externalipsetting} {
		if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-IP EXTERNAL SETUP SECTION - STARTED" }
		set ouripaddress [get_external_IP $externalsiteip $externalsitestartmap $externalsiteendmap]
		if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-old tivo url: >>$dmailTivoURL<<" }
		if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-external ip: >>$ouripaddress<<" }
		if {$oursitesecure} {
			set dmailTivoURL "https://${ouripaddress}"
		} else {
			set dmailTivoURL "http://${ouripaddress}"
		}
		if {$oursiteport != ""} {
			set dmailTivoURL "${dmailTivoURL}:${oursiteport}"
		}
		if {$oursitevirtualpath != ""} {
			set dmailTivoURL "${dmailTivoURL}/${oursitevirtualpath}"
		}
		if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-new tivo url: >>$dmailTivoURL<<" }
		if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-IP EXTERNAL SETUP SECTION - COMPLETED" }
	}
}

## attempt to get mailserver ip if ip not provided using fake dns
catch {
	if { [string first [string range $mailserver 0 0] "0123456789"] < 0 } {
		if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-mailserver not an ip - attempt to get ip via fake dns" }
		if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-mailserver url : >>$mailserver<<" }
		set mailserver [fake_dns $mailserver]
		if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-mailserver ip : >>$mailserver<<" }
	}
}

## setup the unique id required for the cid for the image embedding option
set uniquecontentid "[clock seconds].$mailserver.$dmailHoursahead.$debuglvl$midthreshold$highthreshold$programbarwidthpercent$emergencytempcentigrade$listseperatoroffset"

## setup the image file name array required for image embedding option
set imagenamelist "$tivologofilename $tivofilename $tivobrokenfilename $phonefilename $phonebrokenfilename $diskfilename $diskbrokenfilename $diskfullfilename $diskfullbrokenfilename $endpadonfilename $endpadofffilename $mailfilename $reddotonfilename $reddotofffilename $spacegraphicstart $spacegraphiclow $spacegraphicmid $spacegraphichigh $spacegraphicempty $spacegraphicend $explicitonethumbupgraphic $explicittwothumbupgraphic $explicitthreethumbupgraphic $explicitonethumbdowngraphic $explicittwothumbdowngraphic $explicitthreethumbdowngraphic $impliedonethumbupgraphic $impliedtwothumbupgraphic $impliedthreethumbupgraphic $impliedonethumbdowngraphic $impliedtwothumbdowngraphic $impliedthreethumbdowngraphic $predictedonethumbupgraphic $predictedtwothumbupgraphic $predictedthreethumbupgraphic $predictedonethumbdowngraphic $predictedtwothumbdowngraphic $predictedthreethumbdowngraphic $unsetthumbsgraphic $endpadrecordingunlikelygraphic $emergencytempfilename $optionalmessagefilename $mutideletefilename $multiupdatethumbsfilename $multiupdatethumbsblankboxfilename $trackerblockfilename $spacegraphicextra $suggestiongraphic $exclaimgraphic $startpaddinggraphic $endpaddinggraphic $spaceaddedbackfilename $deleteforroomfilename $flashingexclaimgraphic $newepisodegraphic $seasonpassgraphic $spacebarinfographic $unblockmegraphic $blockmegraphic"
if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-compiled image name list: >>$imagenamelist<<" }

## move the list seperator offset from hours to seconds
set listseperatoroffset [expr $listseperatoroffset * 3600]

## sort out table width in px
set programbarwidthpx [expr round($programbarwidthpercent * 7.5) ]

if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GLOBAL VARIABLE DEFINITION - COMPLETED" }


	#######################################################################################################
	# 2. Handle freepages memory adjustment
	
	if {$freepagesadjustment} {
		if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-MEMORY FREEPAGES ADJUSTMENT - START" }
		if { [ catch { 
			set opt [open /proc/sys/vm/freepages "w"] 
			puts $opt "128 192 256"
			close $opt
			after 2000
		} ] } {
			if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Memory freepages adjustment caused ERROR" }
		} else {
			if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-successfully completed memory freepages adjustment" }
		}
		catch {	unset opt }
	}
	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-MEMORY FREEPAGES ADJUSTMENT - COMPLETED" }

	# END 2.
	#######################################################################################################
	
	
	#######################################################################################################
	# 4. Handle fakecall module
	
	if {$runfakecallmodule} {
		if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-FAKECALL FUNCTIONALITY - START" }
		if { [ catch { set execoutput [exec $fakecallexec] } ] } {
			if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Fakecall module caused an ERROR" }
		} else {
			if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Successfully completed running fakecall module" }
		}
		catch { unset execoutput }
		if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-FAKECALL FUNCTIONALITY - COMPLETED" }
	}
	
	# END 4.
	#######################################################################################################

if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-commence fooling tivoweb modules" }

#needed to fool TiVoWeb modules that they are being called by TiVoWeb :)
global reload
global dlc
set reload 1
set dlc 1
set channeltablefsid {}

if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-completed fooling tivoweb modules" }

setpri fifo 1
catch {EnableTransactionHoldoff true}

proc strim {str} {
	return [string trim $str "\{\}"]
	catch { unset str }
}

if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-completed other preperation" }


###############################################
## sort out arguments passed in

set argument1  [lindex $argv 0]
set argument2  [lindex $argv 1]
set argument3  [lindex $argv 2]
set argument4  [lindex $argv 3]

set originalhoursahead $dmailHoursahead
set originalrecipient $recipient
set originalrecipient2 $recipient2
set originalrecipient3 $recipient3

if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-argument 1 passed in ::: >>$argument1<<" }
if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-argument 2 passed in ::: >>$argument2<<" }
if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-argument 3 passed in ::: >>$argument3<<" }
if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-argument 4 passed in ::: >>$argument4<<" }

set numargs 0

###############################################
## count those arguments

if { $argument1 != "" } {
	set numargs [expr $numargs + 1]
}
if { $argument2 != "" } {
	set numargs [expr $numargs + 1]
}
if { $argument3 != "" } {
	set numargs [expr $numargs + 1]
}
if { $argument4 != "" } {
	set numargs [expr $numargs + 1]
}
if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-$numargs argument(s) found" }


set emailonefound 0
set emailtwofound 0
set emailthreefound 0
set hoursfound 0
set hoursahead -1
set numemails 0
set recipient2 ""
set recipient3 ""


###############################################
## check out argument 1

if { [string first "@" $argument1] > -1  && [string first "." $argument1] > -1 && $argument1 != ""} {
	set numemails [expr $numemails + 1]
	if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-a new recipient email found in argument 1" }
	set emailonefound 1
	set recipient $argument1
} else {
	if { $numargs > 0 } {
		set hoursfound 1
		set hoursahead $argument1
		if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-a new hours ahead value found in argument 1" }
	}

}

###############################################
## check out argument 2

if { [string first "@" $argument2] > -1  && [string first "." $argument2] > -1 && $argument2 != ""} {
	set numemails [expr $numemails + 1]
	if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-a new recipient email found in argument 2" }
	if { $emailonefound != 0} {
		set emailtwofound 2
		set recipient2 $argument2
	} else {
		set emailonefound 2
		set recipient $argument2
	}
} elseif { $numargs > 1 && $hoursfound == 0 } {
		set hoursfound 2
		set hoursahead $argument2
		if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-a new hours ahead value found in argument 2" }
		
}

###############################################
## check out argument 3

if { [string first "@" $argument3] > -1  && [string first "." $argument3] > -1 && $argument3 != ""} {
	set numemails [expr $numemails + 1]
	if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-a new recipient email found in argument 3" }
	if { $emailonefound != 0} {
		if { $emailtwofound != 0} {
			set emailthreefound 3
			set recipient3 $argument3
		} else {
			set emailtwofound 3
			set recipient2 $argument3
		}
	} else {
		set emailonefound 3
		set recipient $argument3

	}
} elseif { $numargs > 2 && $hoursfound == 0 } {
		set hoursfound 3
		set hoursahead $argument3
		if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-a new hours ahead value found in argument 3" }
}

###############################################
## check out argument 4

if { [string first "@" $argument4] > -1  && [string first "." $argument4] > -1 && $argument4 != ""} {
	if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-a new recipient email found in argument 4" }
	set numemails [expr $numemails + 1]
	if { $emailonefound != 0} {
		if { $emailtwofound != 0} {
			set emailthreefound 4
			set recipient3 $argument4
		} else {
			set emailtwofound 4
			set recipient2 $argument4
		}
	} else {
		set emailonefound 4
		set recipient $argument4

	}
} elseif { $numargs > 3 && $hoursfound == 0 } {
		set hoursfound 4
		set hoursahead $argument4
		if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-a new hours ahead value found in argument 4" }
}

catch { unset argument1 }
catch { unset argument2 }
catch { unset argument3 }
catch { unset argument4 }


###############################################
## if too many emails sent in the sort that out

if {$numemails > 3} {
	set numemails 3
	if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-only 3 email recipients allowed - discarding number 4" }
}

###############################################
## sort out an hour variable if entered
	
if { $hoursfound > 0 } {
	if {$dmailHoursahead <= 0  || $dmailHoursahead > 500} {
		if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Hours in syntax incorrect - use integers!" }
		if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Using original hours defined in configuration file!" }
		if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Remember - an email recipient must be in format xxxxxxxx@xxxxxxx.xx" }
		set dmailHoursahead $originalhoursahead
	} else {
		set dmailHoursahead $hoursahead
		if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-hours ahead value is now : >>$dmailHoursahead<<" }
	}
} 


###############################################
## sort out email recipient variable if entered

# if any emails are sent via arguments - then all default ones are cleared
## if no emails are sent via argument - then original emails stand
if {$numemails == 0} {
	set recipient $originalrecipient
	set recipient2 $originalrecipient2
	set recipient3 $originalrecipient3
}

if {$debuglvl>0} {
	if { $emailonefound > 0 || $emailtwofound > 0 || $emailthreefound > 0} {
		if {$recipient!=""} {puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-recipient email value is now : >>$recipient<<" }
		if {$recipient2!=""} {puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-recipient2 email value is now : >>$recipient2<<" }
		if {$recipient3!=""} {puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-recipient3 email value is now : >>$recipient3<<" }
	} 
}

if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-argument handling complete" }

catch { unset emailonefound }
catch {	unset emailtwofound }
catch {	unset emailthreefound }
catch {	unset hoursfound }
catch {	unset numemails }
catch {	unset originalrecipient }
catch {	unset originalrecipient2 }
catch {	unset originalrecipient3 }
catch { unset numargs }



######################################################################
## message handling

if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-start optional message handling" }

	set optionalmsg {}
	
	if { [file exists $msgfilename] } {
		if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-message file found" }
		catch {
			set fsize [file size "$msgfilename"]
			if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-fsize : >>$fsize<<" }
			set msgfile [open "$msgfilename" "r"]
			while { ! [eof $msgfile] } {
				set line [gets $msgfile]
				if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-line : >>$line<<" }
				if {$line != ""} {
					 lappend optionalmsg $line
				}
			}
			close $msgfile
		}
		catch {
			if {$debuglvl>1} {puts  "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-about to delete message file" }
			file delete -force $msgfilename
			if {$debuglvl>1} {puts  "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-message file deleted" }
		}
	} else {
		if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-no message file found"}
	}
	

if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-end optional message handling" }

catch {	unset fsize }
catch {	unset line }
catch {	unset msgfilename }
catch {	unset msgfile }

## end of message handling
######################################################################


#####################################################
## From TiVoWeb's ui.itcl
##  Copyright (c) 2002 Aaron Schrab <aaron@schrab.com>

proc alt_showing_conf {tofind_tmsid tofind_fsid} {
	global db
	global version
	set showings [get_programshowings $tofind_fsid 1]
	foreach showing $showings {
		set seconds [lindex $showing 0]
		set stationfsid [lindex $showing 1]
		set date [expr $seconds / 86400]
		set time [expr $seconds % 86400]
		set timestr [format "%05d" $time]
		ForeachMfsFile recfsid name type "/Recording/Active" "4:$date:$timestr:" {
			RetryTransaction {
				set rec [db $db openid $recfsid]
				set show [dbobj $rec get Showing]
				set prog [dbobj $show get Program]
				set id [dbobj $prog get TmsId]
				if {$id == $tofind_tmsid} {
					catch {	unset seconds }
					catch {	unset stationfsid }
					catch {	unset date }
					catch {	unset time }
					catch {	unset timestr }
					catch {	unset rec }
					catch { unset prog }
					catch {	unset id }
					return "todo [dbobj $show fsid]/[dbobj $show subobjid]"
				}
				catch {	unset rec }
				catch {	unsed prog }
				catch {	unset id }
				catch {	unset show }
			}
		}
		catch {	unset seconds }
		catch {	unset stationfsid }
		catch {	unset date  }
		catch {	unset time }
		catch {	unset timestr }
	}
	# Also check if it's in Now Showing
	ForeachMfsFile recfsid name type  "/Recording/TmsId" "$tofind_tmsid:" {
		RetryTransaction {
			set rec [db $db openid $recfsid]
			set show [dbobj $rec get Showing]
			catch { unset rec }
			return "nowshowing [dbobj $show fsid]/[dbobj $show subobjid]"
		}
	}
	return ""
}



#####################################################
## From TiVoWeb's httpd-tt.tcl by mbm

proc get_tzoffset {mfstz dst override} {
	
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-STARTING GET_TZOFFSET MODULE " }
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - Checkpoint #1 " }
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - mfstz = >>$mfstz<<" }
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - dst = >>$dst<<" }
	if {$override} {
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - value was overrided!" }
		set tz $mfstz
	} else {
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - value was not overrided!" }
		if { $mfstz <= 0 } {
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - Checkpoint #2a " }
			set tz $mfstz
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - tz = >>$tz<<" }
		} else {
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - Checkpoint #2b " }
			set tzlist "-5 -6 -7 -8 -9 -10 0 1 2 3 4 5 6 7 8 9 10 11 12 -1 -2 -3 -4 -11 -12"
			set tz [lindex $tzlist [expr $mfstz - 1]]
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - tz = >>$tz<<" }
		}
	}
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - Checkpoint #3 " }
	if { $dst == 2 } {
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - Checkpoint #4 " }
		set date [clock format [clock seconds] -format "%1d %w %1m %1H %1M"]
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - date = >>$date<<" }
		scan $date "%d %d %d %d %d" dom dow month hour min
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - dom = >>$dom<<" }
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - dow = >>$dow<<" }
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - month = >>$month<<" }
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - hour = >>$hour<<" }
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - min = >>$min<<" }
		set dlsval 0
		if {$::uktivo} {
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - Checkpoint #5a " }
			if {$month > 3 && $month < 10} {
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - Checkpoint #5ai " }
				set dlsval 1
			} elseif {$month == 3 && $dom >= 25 && $dow == 0 && $hour >= 1} {
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - Checkpoint #5aii " }
				set dlsval 1
			} elseif {$month == 3 && $dom >= 25 && $dow != 0 && ($dom-24-$dow >= 1) } {
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - Checkpoint #5iii " }
				set dlsval 1
			}
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - dlsval = >>$dlsval<<" }
		} else {
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - Checkpoint #5b " }
			if {$month > 4 && $month < 10} {
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - Checkpoint #5bi " }
				set dlsval 1
			} elseif {$month == 4 && $dom > 7} {
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - Checkpoint #5bii " }
				set dlsval 1
			} elseif {$month == 4 && $dom <= 7 && $dow == 0 && $hour >= 2} {
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - Checkpoint #5biii " }
				set dlsval 1
			} elseif {$month == 4 && $dom <= 7 && $dow != 0 && ($dom-$dow > 0)} {
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - Checkpoint #5iv " }
				set dlsval 1
			}
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - dlsval = >>$dlsval<<" }
		}
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - Checkpoint #6 " }
		if {$dlsval == 0} {
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - Checkpoint 7 " }
			if {$month == 10 && $dom < 25} {
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - Checkpoint #7a " }
				set dlsval 1
			} elseif {$month == 10 && $dom >= 25 && $dow == 0 && $hour < 2} {
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - Checkpoint #7b " }
				set dlsval 1
			} elseif {$month == 10 && $dom >= 25 && $dow != 0 && ($dom-24-$dow < 1) } {
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - Checkpoint #7c " }
				set dlsval 1
			}
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - Checkpoint #8 " }
		}
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - Checkpoint #9 " }
		if {$dlsval == 1} {
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - Checkpoint #10 " }
			if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-tzoffset : >>[expr $tz+3600]<<" }
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-COMPLETED GET_TZOFFSET MODULE " }
			return [expr $tz+3600]
			
		} else {
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - Checkpoint #11 " }
			if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-tzoffset : >>return [expr $tz]<<" }
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-COMPLETED GET_TZOFFSET MODULE " }
			return [expr $tz]
		}
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - Checkpoint #12 " }
	} else {
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GET_TZOFFSET - Checkpoint #13 " }
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-tzoffset : >>return [expr $tz]<<" }
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-COMPLETED GET_TZOFFSET MODULE " }
		return [expr $tz]
	}
}



#####################################################
## Sends results as an email

proc sendmail {mailserver domain recipient subject htmlfilename} {

	global errorInfo
	
	## temptext is used to hold the entire email html body to search within to see if images are required for the embedded option
	set temptext ""
	
	if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-entered sendmail procedure" }
	if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-variable check:" }
	if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-mailserver : >>$mailserver<<" }
	if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-domain : >>$domain<<" }
	if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-recipient : >>$recipient<<" }
	if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-subject: >>$subject<<" }
	if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-attempting to open socket 25 to mailserver specified >>$mailserver<<" }
	if {$::tivowebplususer} {
		set chan [socket -myaddr $::tivoip $mailserver 25]
	} else {
		set chan [socket $mailserver 25]
	}
	gets $chan reply
	while {[string range $reply 3 3] == "-"} {
		gets $chan reply
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-got reply (multi-line) : >>$reply<<" }
	}
	if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-got reply : >>$reply<<" }
	#<server>220 [server name] [server capabilities]
	if {[lindex $reply 0] != "220"} {
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-bad connection" }
		exit 0
	} else {
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-connected" }
	}
	fconfigure $chan -buffering line -buffersize 4096
	### Try a EHLO as this provides lots of info on allowed authorization for debugging purposes
	puts $chan "EHLO $domain"
	flush $chan
	gets $chan reply
	while {[string range $reply 3 3] == "-"} {
		gets $chan reply
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-got reply (multi-line) : >>$reply<<" }
	}
	if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-got reply : >>$reply<<" }
	#<server>250 [informational message, usually server name]
	if {[string range $reply 0 2] != "250"} {
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ehlo rejected" }
		## try an HELO instead
		puts $chan "HELO $domain"
		flush $chan
		gets $chan reply
		while {[string range $reply 3 3] == "-"} {
			gets $chan reply
			if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-got reply (multi-line) : >>$reply<<" }
		}
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-got reply : >>$reply<<" }
		#<server>250 [informational message, usually server name]
		if {[string range $reply 0 2] != "250"} {
			if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-helo rejected" }
			exit 0
		} else {
			if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-helo acknowledged" }
		}
	} else {
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ehlo acknowledged" }
	}
	if {$::authreq} {
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-AUTH LOGIN authorization required" }
			### specify authorization method
			if {$::authmethod == "PLAIN"} {
				puts $chan "AUTH PLAIN"
			} else {
				puts $chan "AUTH LOGIN"		
			}
			flush $chan
			gets $chan reply
			while {[string range $reply 3 3] == "-"} {
			gets $chan reply
			if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-got reply (multi-line) : >>$reply<<" }
		}
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-got reply : >>$reply<<" }
		#<server>334 [usually username encoded in base 64]
		if {[string range $reply 0 2] != "334"} {
			if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-AUTH $::authmethod authorization method rejected" }
			exit 0
		} else {
			if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-AUTH $::authmethod authorization method accepted" }
		}
		### specify base 64 encoded username
		puts $chan "$::username_base64"
		flush $chan
		gets $chan reply
		while {[string range $reply 3 3] == "-"} {
			gets $chan reply
			if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-got reply (multi-line) : >>$reply<<" }
		}
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-got reply : >>$reply<<" }
		#<server>334 [usually password encoded in base 64]
		if {[string range $reply 0 2] != "334"} {
			if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-username rejected" }
			exit 0
		} else {
			if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-username accepted" }
		}
		### specify base 64 encoded password
		puts $chan "$::password_base64"
		flush $chan
		gets $chan reply
		while {[string range $reply 3 3] == "-"} {
			gets $chan reply
			if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-got reply (multi-line) : >>$reply<<" }
		}
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-got reply : >>$reply<<" }
		#<server>235 [informational message, usually Authentication Successful]
		if {[string range $reply 0 2] != "235"} {
			if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-password incorrect" }
			exit 0
		} else {
			if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-password accepted" }
		}
	}
	puts $chan "MAIL FROM:<$::sender>"
	flush $chan
	gets $chan reply
	while {[string range $reply 3 3] == "-"} {
		gets $chan reply
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-got reply (multi-line) : >>$reply<<" }
	}
	if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-got reply : >>$reply<<" }
	#<server>250 ok
	if {[string range $reply 0 2] != "250"} {
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-connection rejected" }
		exit 0
	} else {
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-from acknowledged" }
	}
	puts $chan "RCPT TO:<$recipient>"
	flush $chan
	gets $chan reply
	while {[string range $reply 3 3] == "-"} {
		gets $chan reply
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-got reply (multi-line) : >>$reply<<" }
	}
	if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-got reply : >>$reply<<" }
	#<server>250 ok
	if {[string range $reply 0 2] != "250"} {
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-connection rejected" }
		exit 0
	} else {
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-to acknowledged" }
	}
	puts $chan "DATA"
	flush $chan
	gets $chan reply
	while {[string range $reply 3 3] == "-"} {
		gets $chan reply
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-got reply (multi-line) : >>$reply<<" }
	}
	if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-got reply : >>$reply<<" }
    	#<server>354 go ahead
	if {[string range $reply 0 2] != "354"} {
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-connection rejected" }
		exit 0
	} else {
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-sending message" }
	}
	if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-building header" }
	
	## send mesage id for email
	puts $chan "Message-ID: <[clock seconds]@$domain>"
	flush $chan

	## send date for email
	if {$::yankspeak} {
		puts $chan "Date: [clock format [clock seconds] -format {%a, %d %b %Y %H:%M:%S (%Z)} -gmt true]"
		append temptext "Date: [clock format [expr [clock seconds] + $::tzoffset] -format {%a, %d %b %Y %H:%M:%S (%Z)} -gmt true]\n"
	} else {
		puts $chan "Date: [clock format [clock seconds] -format {%a, %d %b %Y %H:%M:%S (%Z)} -gmt true]"
		append temptext "Date: [clock format [expr [clock seconds] + $::tzoffset] -format {%a, %d %b %Y %H:%M:%S (%Z)} -gmt true]\n"
	}	
	flush $chan
	
	## send ::sender information for email
	puts $chan "From: \"$::senderName\" <$::sender>"
	flush $chan

	## send MIME information for email
	puts $chan "MIME-Version: 1.0"
	flush $chan
	
	## send recipient information for email
	if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-about to set recipient" }
	puts $chan "To: $recipient"
	flush $chan
	
	## send subject information for email
	puts $chan "Subject: $subject"
	flush $chan
	
	## if image embedding required then we need to define boundary text, define a multipart email and set first boundary
	if { $::embeddedimages } {
		## define boundary text
		set boundaryid "[clock seconds]005928374_dailymail_jazz_boundary"
		## send multipart and boundary info
		puts $chan "Content-Type: multipart/related; boundary=\"==$boundaryid\"; type=\"text/html\""
		flush $chan	
		##send blank line
		puts $chan ""
		flush $chan
		## send first boundary
		puts $chan "--==$boundaryid"
		flush $chan		
	}

	## define the content type for html portion of email
	puts $chan "Content-Type: text/html; charset=us-ascii"
	flush $chan
	
	## define content transfer encoding for html portion of email
	puts $chan "Content-Transfer-Encoding: 7bit"
	flush $chan
	
	## send blank line
	puts $chan ""
	flush $chan
	
	## send HTLM DTD Info
	puts $chan "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2//EN\">"
	flush $chan

	## deal with HTML portion of email
	## if embedding email then we have to use the fragmented write option to populate the temptext variable
	if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-html starts" }
	if {$::fragmenthtmlemailwrite || $::embeddedimages} {
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-require fragmented read / write of email" }
		if { [ catch { 
			set htmlfilefd [open $htmlfilename r] 
		} ] } {
			# nothing
			if {$::debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ERROR - CAN'T OPEN HTML FILE FOR READING" }
			if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
			if {$::debuglvl>0} { puts "$errorInfo"}
			if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
		} else {
			set ourstringlength 0
			set totalstringlength 0
			if {$::debuglvl>2} { puts "---------------------------------------------------------------------------------------------------------------" }
			while {[gets $htmlfilefd activeline] >= 0}  {
				set ourstringlength [string length $activeline]
				set totalstringlength [expr $totalstringlength + $ourstringlength]
				flush $chan
				puts $chan "$activeline"
				if { $::embeddedimages } {
					append temptext "$activeline\n"
				}
				if {$::debuglvl>2} { puts "$ourstringlength bytes (${totalstringlength} bytes) -- $activeline" }
					set ourstringlength 0
			}
			if {$::debuglvl>2} { puts "---------------------------------------------------------------------------------------------------------------" }
			set ourstringlengthmb [expr $totalstringlength / 1024]
			if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-message length: $ourstringlengthmb kilobytes" }
		}
		close $htmlfilefd
		catch { unset activeline }
	} else {
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-require holistic read /write of email" }
		if { [ catch { 
			set htmlfilefd [open $htmlfilename r] 
		} ] } {
			# nothing
			if {$::debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ERROR - CAN'T OPEN HTML FILE FOR READING" }
			if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
			if {$::debuglvl>0} { puts "$errorInfo"}
			if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
		} else {
			flush $chan
			fcopy $htmlfilefd $chan
		}
		close $htmlfilefd
		catch { unset htmlfilefd }
	}
	flush $chan

	## send blank line	
	puts $chan ""
	flush $chan
	
	## handle the adding of the base64 encoded images
	if { $::embeddedimages } {

		set imagecount 0
		set imagesused ""
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-starting image embedding" }
		
		## for each image in the image array
		foreach imagefilename $::imagenamelist {
		
			## do pre-processing to figure out if we need this image to be included
			set imagereq -1
			set imagereq [string first $imagefilename $temptext]
			set imagealready -1
			set imagealready [string first " $imagefilename " " $imagesused "]
			
			## figure out image type i.e. gif or jpg
			set dotloc -1
			set dotloc [string last "." $imagefilename]
			set dotloc [expr $dotloc + 1]
			set imagefiletype "gif"
			set imagefiletype [string range $imagefilename $dotloc 999]
			
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-++++++++++++++++++++++++++++++++++++++++++++++" }
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-filename: >>$imagefilename<<" }
				
			## if the image is required and not already been attached then we need to add the base64 code
			if {$imagereq != -1 && $imagealready == -1 } {	
			
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-image found in body - required" }

				## add image name to the list of images that have already been used
				append imagesused "$imagefilename "
				
				## figure out the filename of the image base64 file
				set imagebase64filename ""
				set imagebase64filename "$::embeddedimagesloc/$imagefilename.txt"
				
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-filename: >>$imagebase64filename<<" }
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-type: >>$imagefiletype<<" }

				## send multipartboundar info
				puts $chan "--==$boundaryid"
				flush $chan	
	
				## send content type for image
				puts $chan "Content-Type: image/$imagefiletype;"
				flush $chan	

				## send content id for image i.e. the cid code
				puts $chan "Content-ID: <$imagefilename.$::uniquecontentid@$domain>"
				flush $chan	

				## send content transfer encoding info for image
				puts $chan "Content-Transfer-Encoding: base64"
				flush $chan	

				## send content disposition and filename info for image
				puts $chan "Content-Disposition: inline; filename=\"$imagefilename\""
				flush $chan	

				## send blank line
				puts $chan ""
				flush $chan

				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-about to open >>$imagebase64filename<< file" }

				## send base64 code
				if { [ catch { 
					set imagefilefd [open $imagebase64filename r] 
				} ] } {
					if {$::debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-file open FAILED" }
					if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
					if {$::debuglvl>0} { puts "$errorInfo"}
					if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
				} else {
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-file open succeeded" }
					while {[gets $imagefilefd activeline] >= 0}  {
						flush $chan
						puts $chan "$activeline"
					}
				}
				flush $chan
				
				## clear various variables down
				catch { close $imagefilefd }
				catch { unset imagefilefd }
				catch { unset activeline }
				

				## send blank line
				puts $chan ""
				flush $chan
				
			} else {
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-image NOT found in body - NOT required" }
			}

			set imagecount [expr $imagecount + 1]

		}
		
	}
	
	catch { unset imagealready }

	puts $chan ""
	flush $chan

	# clear temptext variable down	
	catch { unset temptext }
	
	## send email terminator indicator
	puts $chan "."
	flush $chan	
	gets $chan reply
	while {[string range $reply 3 3] == "-"} {
		gets $chan reply
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-got reply (multi-line) : >>$reply<<" }
	}
	if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-got reply : >>$reply<<" }
	#<server>250 [informational message]
	if {[string range $reply 0 2] != "250"} {
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-sending failed"}
		exit 0
	} else {
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-message sent"}
	}
	puts $chan "quit"
	flush $chan
	gets $chan reply
	while {[string range $reply 3 3] == "-"} {
		gets $chan reply
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-got reply (multi-line) : >>$reply<<" }
	}
	if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-got reply : >>$reply<<" }
	#<server>221 [informational message]
	if {[string range $reply 0 2] != "221"} {
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-disconnect failed"}
		#exit 0 - don't really need to fail fatally at this point.
	} else {
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-disconnected"}
	}
	close $chan
	
	# clear down variables 	
	foreach var [info vars] {
		catch {
			if {$var != ""} {
				if { [catch { 
					if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-unsetting variable >>$var<<"}
				} fid] } {
					# null
				} else {
					if { [catch { 
						unset $var  
					} fid] } {
						if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-error in unsetting variable >>$var<<"}
					} 
				}
			}
		}
	}

}



#####################################################
## Save results as an html file

proc openhtml {} {
	if { $::htmlfilefd == 0 } {
		if { [ catch { set ::htmlfilefd [open $::htmlfilename "w"] } ] } {
		} else {
			puts $::htmlfilefd ""
			puts $::htmlfilefd "<html>"
			puts $::htmlfilefd "<head>"
			outputStyleSheet $::htmlfilefd
			puts $::htmlfilefd "</head>"
			puts $::htmlfilefd "<body>"
		}
	}
}

proc writehtml {message} {
	if { $::htmlfilefd == 0 } {
		openhtml
	}
	if { $::htmlfilefd > 0 } {
		puts $::htmlfilefd $message
		flush $::htmlfilefd
	}
	catch { unset message }
}

proc closehtml {} {
	if { $::htmlfilefd > 0 } {
		puts $::htmlfilefd "</body>"
		puts $::htmlfilefd "</html>"
		flush $::htmlfilefd
		close $::htmlfilefd
		set ::htmlfilefd 0
	}
}

#####################################################
## Get unresolved conflicts

proc getconflicts {hoursahead} {

	set conflictsFound 0
	set oldday ""
	set conflicts {}
	after 2000
	set colourtoggle 1
	ForeachMfsFile fsid name type "/Recording/History" "" {
		set debugfinished false
		set gottabreak false
		catch { 
			set recdate [split $name ":"]
			regsub {^(-?)0+([1-9])} [lindex $recdate 1] {\1\2} thetime
			set rectime [expr ([lindex $recdate 0] * 86400) + $thetime]
			if {$rectime > [expr [clock seconds] + ($hoursahead * 3600)]} {
				set debugfinished true
				set gottabreak true
				break
			}
			if {$rectime > [clock seconds]} {
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-## new program "}
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-item is current"}
				RetryTransaction {
					set rec [db $::db openid $fsid ]
					set creason [dbobj $rec get CancelReason]
					set showing [dbobj $rec get Showing]
					set showingfsid [dbobj $rec gettarget Showing]
					set station [dbobj $showing get Station]
					if {$::version >= 3} {
						set recbeh [dbobj $rec get RecordingBehavior]
						set seltype [dbobj $recbeh get PresentationBehavior]
					} else {
						set seltype [dbobj $rec get SelectionType]
					}
					set callsign [dbobj $station get CallSign]
					set program [dbobj $showing get Program]
					set title [strim [dbobj $program get Title]]
					set id [dbobj $program get TmsId]
					set id2 [dbobj $program fsid]
					set descr [strim [dbobj $program get Description]]
					set series [dbobj $program get Series]
					set seriesfsid [dbobj $series fsid]
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-title : >>$title<<"}
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-id : >>$id<<"}
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-id2 : >>$id2<<"}
					catch { unset rec }
					if {$::yankspeak} {
						set nowday [clock format [expr $rectime +  $::tzoffset - $::listseperatoroffset] -format {%A, %B %d}]
					} else {
						set nowday [clock format [expr $rectime + $::tzoffset  - $::listseperatoroffset] -format {%a, %d %b}]
					}
					if {$series != ""} {
						set episodic [defaultval 1 [dbobj $series get Episodic]]
					} else {
						set episodic 1
					}
					if { $episodic == 1 } {
						set eptitle [strim [dbobj $program get EpisodeTitle]]
						if { $eptitle == "" } {
							set eptitle "No Episode Title"
						}
					} else {
						set eptitle ""
					}
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-episode : >>$eptitle<<"}
				}
				
				## IGNORE SELECTION / PRESENTATION ITEM
				set ignorethisitem "N"
				foreach ignoreitem $::ignorelist {
					if { $ignoreitem ==  $seltype } {
						set ignorethisitem "Y"
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ignore item at user request"}
					}
				}
				##
						
				if {$ignorethisitem == "N"} {
				
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-cancel reason code : >>$creason<<"}
					if {$creason == 20} {
						set alt [alt_showing_conf $id $id2]
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-alternate (alt) : >>$alt<<"}
						if {$alt == ""} {
							if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-alt is blank - assume no alternate - unresolvable"}
							### start blank date row insert 
							if {$::listseperator} {
								if {$oldday != $nowday} {
									writehtml "<tr><td class=seperator>$nowday</td>"
									if {$::dmailLinksOn} {
										writehtml "<td class=links>&nbsp;</td>"	
									}
									writehtml "</tr>"
									set oldday $nowday
								}
							}
							### end blank date row insert
							
							if {$::multicolourbar} {
								set rowclassid "$colourtoggle"
								if {$colourtoggle == 1} {
									set colourtoggle 2
								} else {
									set colourtoggle 1
								}
							} else {
								set rowclassid ""
							}
							writehtml "<tr><td class=programme${rowclassid}><strong>"
							writehtml "$title" 
							writehtml "</strong>"
							if {$::yankspeak} {
								writehtml "[clock format [expr $rectime + $::tzoffset] -format {%a %I:%M%p}] $callsign"
							} else {
								writehtml "[clock format [expr $rectime + $::tzoffset] -format {%a %H:%M}] $callsign"
							}
							writehtml "<br>"
							if {$eptitle !=""} {
								if {$descr !=""} {
									writehtml "$eptitle - $descr"
								} else {
									writehtml "$eptitle"
								}
							} else {
								if {$descr !=""} {
									writehtml "$descr"
								} else {
									writehtml "No description."
								}
							}
							if {$::dmailLinksOn} {
								writehtml "</td><td class=links${rowclassid}>"
								writehtml "<a href=\"$::dmailTivoURL/showing/$showingfsid\" title=\"Click here to view details.\" target=\"_blank\">view details</a><br>"
								writehtml "<a href=\"$::dmailTivoURL/series/$seriesfsid\" title=\"Click here to view available time slots\" target=\"_blank\">view slots </a>"
							}
							writehtml "</td></tr>"
							set conflictsFound 1
							set ::alertstatus true
							append ::alertreasons "Conflict - "
						}
					}
				}
			}
			set debugfinished true
		}
		
		if {$debugfinished} {
			#nothing
		} else {
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-conflict error occurred with item"}
		}
		if {$gottabreak} {
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-quit out of conflict loop"}
			break
		}
	}
	
	# clear down variables 	
	foreach var [info vars] {
		catch {
			if {$var != "conflictsFound"} {
				if { [catch { 
					if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-unsetting variable >>$var<<"}
				} fid] } {
					# null
				} else {
					if { [catch { 
						unset $var  
					} fid] } {
						if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-error in unsetting variable >>$var<<"}
					} 
				}
			}
		}
	}
	
	return $conflictsFound
	catch { unset conflictsFound}
}



#####################################################
## Generate Now Showing List

proc getnowshowing {} {
	
	set message {}
	after 2000
	set nowshowingcount 0
	set repeatbarcount 0
	set progressivethumbs "999999999"
	set colourtoggle 1
	set sortedlist {}
	set unsortedlist {}
	set sortcount 0

	if {$::yankspeak} {
		set program_word "rogram"
	} else {
		set program_word "rogramme"
	}
	
	## GLOBAL BLOCKLIST SETUP CODE
	
	if {$::globalblockreq} {
	
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-start global block list setup"}
	
		proc gbl_load {filename} {
			if {![file exists $filename]} {
				set openfile [open $filename w]
				close $openfile
			}
			set openfile [open $filename r]
			set ret [read $openfile]
			close $openfile
			return $ret
		}

		proc gbl_andlogic {element description} {
			set ret $element
			while {[string match "*+*" $element] == 1} {
				set sliceright [string first "+" $element]
				set sliceleft [expr {$sliceright - 1}]
				incr sliceright
				set stringbit [string range $element 0 $sliceleft]
				set element [string range $element $sliceright end]
				if {[string match [string tolower *$stringbit*] [string tolower $description]] == 0} {
					set ret 0
				}		
			}
			if {[string match [string tolower *$element*] [string tolower $description]] == 0} {
				set ret 0
			}	
			return $ret
		}

		set globalblocklist [gbl_load "/var/hack/blocklist.txt"]
		set globalblockpatt [gbl_load "/var/hack/blockpatt.txt"]
		
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-end global block list setup"}
		
	}
	
	## END GLOBAL BLOCKLIST SETUP CODE
	
	ForeachMfsFileTrans fsid name type $::nowshowingdir "" 10 {
	
		catch {
		
			set rec [db $::db openid $fsid]	
			set expdate [dbobj $rec get ExpirationDate]
			set expsecs [expr $expdate * 86400 + [dbobj $rec get ExpirationTime]]
			set showing [dbobj $rec get Showing]
			set showingfsid [dbobj $rec gettarget Showing]
			set startdate [dbobj $rec get StartDate]
			set starttime 0
			set starttime [dbobj $rec get StartTime]
			if { $starttime == "" } {
				set starttime [dbobj $showing get Time]
			}
			if {$starttime == ""} {
				set starttime 0
			}
			set rectime [expr $startdate * 86400 + $starttime]
			set station [dbobj $showing get Station]
			set stationfsid [dbobj $station fsid]
			set callsign [dbobj $station get CallSign]
			set program [dbobj $showing get Program]
			set title [strim [dbobj $program get Title]]
			set descr [strim [dbobj $program get Description]]
			set series [dbobj $program get Series]
			set duration [dbobj $showing get Duration]
			set durationminutes [expr $duration / 60]

			if {[dbobj $program get OriginalAirDate] == [dbobj $showing get Date]} {
				set airdatestr "First Showing"
			} else {
				set airdatestr ""
			}

			set premiere [strim [dbobj $showing get Premiere]]
			if {$premiere != ""} {
				switch $premiere {
					"0"	{ set premstr "Season Finale" }
					"1"	{ set premstr "Series Finale" }
					"2"	{ set premstr "Premiere" }
					"3"	{ set premstr "Season Premiere" }
					"4"	{ set premstr "Series Premiere" }
					default	{ set premstr "" }
				}
			} else {
				set premstr ""
			}

			if {$::version >= 3} {
				set recbeh [dbobj $rec get RecordingBehavior]
				set seltype [dbobj $recbeh get PresentationBehavior]
			} else {
				set seltype [dbobj $rec get SelectionType]
			}

			if {$series != ""} {
				set episodic [defaultval 1 [dbobj $series get Episodic]]
			} else {
				set episodic 1
			}

			if { $episodic == 1 } {
				set eptitle [strim [dbobj $program get EpisodeTitle]]
				if { $eptitle == "" } {
					set eptitle "No Episode Title"
				}
			} else {
				set eptitle ""
			}

			if { $episodic == 1 } {
				set eptitlexx [strim [dbobj $program get EpisodeTitle]]
			} else {
				set eptitlexx ""
			}

			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-----new programme >>$title<<"}

			## IGNORE SELECTION / PRESENTATION ITEM 
			set ignorethisitem "N"
			foreach ignoreitem $::ignorelist {
				if { $ignoreitem ==  $seltype } {
					set ignorethisitem "Y"
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ignore item at user request"}
				}
			}

			##

			## we want to ignore INVISIBLE program types as they just cause trouble and are not real programs but other data
			if { ( $::version >= 3 && $seltype != 8 ) || $::version < 3 } {

				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-item not invisible"}

				if {$ignorethisitem == "N"} {

					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-item not ignored"}

					if {$::nowshowingdaylimit == 0 || $rectime > [expr [clock seconds] - ( $::nowshowingdaylimit * 86400 ) ] } {

						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-item not out of date range"}

						## INITIAL THUMBS SETUP

						set seriesfsid ""
						set thumbs ""
						set imagef ""
						set thumbcount 0
						set thumbtype ""
						set xthumbtype ""
						set series [dbobj $program get Series]

						if {$::viewthumbs || $::todomultithumbupdate} {

							if { $series != "" } {
								if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-calculating thumbs"}   
								set seriesfsid [dbobj $series fsid]
								set score [dbobj $series get ThumbData]
								if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-score >>$score<<"}   
								if { $score != "" } {
									set thumbdata [ReadableThumbs $score]
									if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-thumb data >>$thumbdata<<"}   
									scan $thumbdata "%s %d %d" thumbtype numthumbs thumbconf
									if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-thumbtype >>$thumbtype<< | numthumbs >>$numthumbs<< | thumbconf >>$thumbconf<<"} 
									if {$thumbtype == "Predicted"} {
										switch -- $numthumbs {
											3	{set imagef "$::predictedthreethumbupgraphic" }
											2	{set imagef "$::predictedtwothumbupgraphic" }
											1	{set imagef "$::predictedonethumbupgraphic"  }
											0	{set imagef ""} 
											-1	{set imagef "$::predictedonethumbdowngraphic" }
											-2	{set imagef "$::predictedtwothumbdowngraphic" }
											-3	{set imagef "$::predictedthreethumbdowngraphic" }
											default {set imagef "" }
										}
										set thumbtype "P"
										set thumbcount $numthumbs
										set xthumbtype "Predicted"
									} elseif {$thumbtype=="Explicit"} {
										switch -- $numthumbs {
											3	{set imagef "$::explicitthreethumbupgraphic" }
											2	{set imagef "$::explicittwothumbupgraphic" }
											1	{set imagef "$::explicitonethumbupgraphic"  }
											0	{set imagef "" }
											-1	{set imagef "$::explicitonethumbdowngraphic" }
											-2	{set imagef "$::explicittwothumbdowngraphic" }
											-3	{set imagef "$::explicitthreethumbdowngraphic" }
											default {set imagef "" } 
										}
										set thumbtype "E"
										set thumbcount $numthumbs
										set xthumbtype "Explicit"
									} elseif {$thumbtype=="Implicit" || $thumbtype=="Implied"} {
										switch -- $numthumbs {
											3	{set imagef "$::impliedthreethumbupgraphic" }
											2	{set imagef "$::impliedtwothumbupgraphic" }
											1	{set imagef "$::impliedonethumbupgraphic" }
											0	{set imagef "" }
											-1	{set imagef "$::impliedonethumbdowngraphic" }
											-2	{set imagef "$::impliedtwothumbdowngraphic" }
											-3	{set imagef "$::impliedthreethumbdowngraphic" }
											default {set imagef "" }
										}
										set thumbtype "I"
										set thumbcount $numthumbs
										set xthumbtype "Implied"
									} else {
										set thumbtype "I"
										set thumbcount 0
										set imagef $::unsetthumbsgraphic
										set xthumbtype "Implied"
									}
									if {$imagef==""} {
										set imagef $::unsetthumbsgraphic
									}
									if {$thumbtype==""} {
										set thumbtype "I"
										set xthumbtype "Implied"
									}
									if {$numthumbs==""} {
										set numthumbs 0
									}
									if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-thumb image >>$imagef<< | thumb count >>$thumbcount<< | thumb type >>$thumbtype<< | expanded thumb type >>$xthumbtype<<"}   
								} else {
									set imagef $::unsetthumbsgraphic
									set thumbtype "I"
									set numthumbs 0
									set xthumbtype "Implied"							
								}
							}

						}

						## END OF INITIAL THUMB SETUP

						lappend unsortedlist [list "${title}${eptitlexx}${rectime}" $title $expsecs $rectime $callsign $durationminutes $seltype $eptitle $descr $fsid $showingfsid $imagef $xthumbtype $thumbcount $thumbtype $seriesfsid $thumbs $series $airdatestr $premstr ]				
						set sortcount [expr $sortcount + 1]	

					}

				}

			}

		}
	}
	
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-about to clear old variables"} 
							
	catch {unset title }
	catch {unset expsecs }
	catch {unset rectimeset }
	catch {unset callsign }
	catch {unset durationminutes }
	catch {unset seltype }
	catch {unset eptitle }
	catch {unset descr }
	catch {unset fsid }
	catch {unset showingfsid }
	catch {unset imagef }
	catch {unset xthumbtype }
	catch {unset thumbcount }
	catch {unset thumbtype }
	catch {unset seriesfsid }
	catch {unset thumbs }
	catch {unset series }
	catch {unset airdatestr }
	catch {unset premstr }
	
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-about to sort lists"} 
	
	if {$::sortnowshowing == ""} {
		set sortedlist $unsortedlist
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-no sorting required"} 
	} else {
		if {$::sortnowshowing == "TITLE"} {
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-title sorting required"} 
			if {$::sortnowshowingascdesc == "ASC" || $::sortnowshowingascdesc == "" } {
				set sortedlist [lsort -dictionary -increasing -index 0 $unsortedlist]
			} else {
				set sortedlist [lsort -dictionary -decreasing -index 0 $unsortedlist]
			}
		}

		if {$::sortnowshowing == "RECTIME"} {
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-rectime sorting required"} 
			if {$::sortnowshowingascdesc == "ASC" || $::sortnowshowingascdesc == "" } {
				set sortedlist [lsort -integer -increasing -index 3 $unsortedlist]
			} else {
				set sortedlist [lsort -integer -decreasing -index 3 $unsortedlist]
			}		
		}

		if {$::sortnowshowing == "EXPTIME"} {
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-exptime sorting required"} 
			if {$::sortnowshowingascdesc == "ASC" || $::sortnowshowingascdesc == "" } {
				set sortedlist [lsort -integer -increasing -index 2 $unsortedlist]
			} else {
				set sortedlist [lsort -integer -decreasing -index 2 $unsortedlist]
			}
		}

		if {$::sortnowshowing == "CALLSIGN"} {
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-callsign sorting required"} 
			if {$::sortnowshowingascdesc == "ASC" || $::sortnowshowingascdesc == "" } {
				set sortedlist [lsort -dictionary -increasing -index 4 $unsortedlist]
			} else {
				set sortedlist [lsort -dictionary -decreasing -index 4 $unsortedlist]
			}
		}
	}	
	
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-sorting complete"} 
	
	set donecount 0
	
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-about to handle main display loop"} 
	
	while { $donecount <= $sortcount } {
	
		set totalitem ""
		set totalitem [lindex $sortedlist $donecount]
		
		set title [lindex $totalitem 1]
		set expsecs [lindex $totalitem 2]
		set rectime [lindex $totalitem 3]
		set callsign [lindex $totalitem 4]
		set durationminutes [lindex $totalitem 5]
		set seltype [lindex $totalitem 6]
		set eptitle [lindex $totalitem 7]
		set descr [lindex $totalitem 8]
		set fsid [lindex $totalitem 9]
		set showingfsid [lindex $totalitem 10]
		set imagef [lindex $totalitem 11]
		set xthumbtype [lindex $totalitem 12]
		set thumbcount [lindex $totalitem 13]
		set thumbtype [lindex $totalitem 14]
		set seriesfsid [lindex $totalitem 15]
		set thumbs [lindex $totalitem 16]
		set series [lindex $totalitem 17]
		set airdatestr [lindex $totalitem 18]
		set premstr [lindex $totalitem 19]
		
		if {$title != ""} {
		
			if {$seltype != 6 || $::dmailShowSuggestions} {
				
				## Start blank row insert
				if {$nowshowingcount == 0 || ( $repeatbarcount == $::nowshowingrepeatfreq && $::nowshowingrepeatfreq != 0 ) } {
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-blank row creation"} 
					set repeatbarcount 0
					writehtml "<tr><td class=seperator>&nbsp</td>"
					if {$::dmailLinksOn} {
						writehtml "<td class=links>&nbsp;</td>"				
					}
					if {$::viewthumbs} {
						writehtml "<td class=thumbs>&nbsp;</td>"			
					}
					## for multi-thumb update
					if {$::tivowebplususer} {
						## null
					} else {
						if {$::series1} {
							if {$::todomultithumbupdate} {
								if {$::dmailLinksOn} {
									if {$::graphicson} {
										writehtml "<td class=thumbupdate><input type=\"image\" src=\"[imageref $::multiupdatethumbsfilename]\" value=\"Submit\" name=\"ThumbUpdate_NowShowing\" title=\"Update thumb settings for p${program_word}s in the now showing list.\" alt=\"Update\"></a></td>"
									} else {
										writehtml "<td class=thumbupdate><center><input type=\"submit\" Name=\"ThumbUpdate_NowShowing\" value=\"update\" style=\"height: 22px; font-size: 8pt; width: 50px;\"></center></td>"	           	
									}
								}
							}
						}
					}
					## for checkbox action items
					if {$::todomultidelete} {
						if {$::dmailLinksOn} {
							if {$::graphicson} {
								writehtml "<td class=action><input type=\"image\" src=\"[imageref $::mutideletefilename]\" value=\"Submit\" name=\"Delete_NowShowing\" title=\"Delete selected p${program_word}s from the now showing list.\" alt=\"Delete\"></a></td>"
							} else {
								writehtml "<td class=action><center><input type=\"submit\" Name=\"Delete_NowShowing\" value=\"del\" style=\"height: 22px; font-size: 8pt; width: 36px;\"></center></td>"
							}
						}
					} 
					writehtml "</tr>"

				}
				### End of blank date row insert

				if {$::multicolourbar} {
					set rowclassid "$colourtoggle"
					if {$colourtoggle == 1} {
						set colourtoggle 2
					} else {
						set colourtoggle 1
					}
				} else {
					set rowclassid ""
				}

				if { $expsecs < [expr [clock seconds] + ( 2 * 86400 ) ] } {
					if { $expsecs < [expr [clock seconds] - ( 1 * 86400 ) ] } {
						writehtml "<tr><td class=programme${rowclassid}>"
					} else {
						writehtml "<tr><td class=unresolved>"
					}
				} else {
					writehtml "<tr><td class=programme${rowclassid}>"
				}

				writehtml "<table border=0 cellspacing=0 cellpadding=0><tr><td valign=middle class=invisible><strong>"
				writehtml "$title" 
				writehtml "</strong>"

				## we only want to display expiration time for those items expiring in the next 45 days
				if { $expsecs < [expr [clock seconds] + ( 45 * 86400 ) ] } {
					set expirypertinent true
				} else {
					set expirypertinent false
				}

				if {$::yankspeak} {
					writehtml "Recorded [clock format [expr $rectime + $::tzoffset] -format {%A, %B %d %I:%M%p}] $callsign \[${durationminutes} Min\]"
					if { $expirypertinent } {
						if { $expsecs < [expr [clock seconds] + ( 2 * 86400 ) ] } {
							if { $expsecs < [clock seconds] } {
								writehtml " - <b>Expired</b>"
							} else {
								writehtml " - <b>Expires [clock format [expr $expsecs + $::tzoffset] -format {%A, %B %d %I:%M%p}]</b>"
							}
						} else {
							writehtml " - Expires [clock format [expr $expsecs + $::tzoffset] -format {%A, %B %d %I:%M%p}]"
						}
					}
				} else {
					writehtml "Recorded [clock format [expr $rectime + $::tzoffset] -format {%a, %d %b %H:%M}] $callsign \[${durationminutes} Min\]"
					if { $expirypertinent } {
						if { $expsecs < [expr [clock seconds] + ( 2 * 86400 ) ] } {
							if { $expsecs < [clock seconds] } {
								writehtml " - <b>Expired</b>"
							} else {
								writehtml " - <b>Expires [clock format [expr $expsecs + $::tzoffset] -format {%a, %d %b %H:%M}]</b>"
							}
						} else {
							writehtml " - Expires [clock format [expr $expsecs + $::tzoffset] -format {%a, %d %b %H:%M}]"
						}
					}
				}	
				if {$seltype == 6} {
					if {$::suggestiongraphicreq} {
						if {$::graphicson} {
							writehtml "</td><td valign=middle class=invisible>&nbsp;<img src=\"[imageref $::suggestiongraphic]\" border=\"0\" title=\"Suggestion\" alt=\"Sug\">"
						} else {
							writehtml "&nbsp;SUG"
						}
					} else {
						writehtml "&nbsp;(Suggestion)"
					}
				} 

				## Global blocklist functionality

				set blockthis ""
				set globalblock ""

				if {$::globalblockreq} {

					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-global blocker start"}

					set pattmatch 0
					set andmatch 0
					foreach element $globalblockpatt {
						if {[string match "*+*" $element]} {
							set andmatch [gbl_andlogic $element $eptitle$descr]
							if {$andmatch != 0} {
								set pattmatch $andmatch
							}
						} elseif {[string match [string tolower *$element*] [string tolower $eptitle$descr]] == 1} {
							set pattmatch $element
						}
					}
					if {[lsearch [string tolower $globalblocklist] [string tolower $title]] >= 0} {
						# match with title
						set blockthis "Yes"
						set globalblock "Yes"
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-global blocker- item will be marked"}
					} elseif {$pattmatch != 0} {
						# match with pattern
						set blockthis "Yes"
						set globalblock "Yes"
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-global blocker- item will be marked"}
					} else {
						# no match with pattern
						# do nothing
					}

					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-global blocker start"}
				}

				## End of global blocklist functionality

				## Global Block Extra Functionality function

				if { $::dmailLinksOn && $::globalblockfunction} {
					if { $globalblock == "Yes" } {
						if {$::graphicson} {
							writehtml "</td><td valign=middle class=invisible>&nbsp;<a href=\"$::dmailTivoURL/blocklist_addremove/$title\" title=\"Click here to remove this title from your global block list.\" target=\"_blank\"><img src=\"[imageref $::unblockmegraphic]\" border=\"0\" title=\"Click here to remove this title from your global block list.\" alt=\"U\"></a>\n"										
						} else {
							writehtml"</td><td valign=middle class=invisible>&nbsp;<a href=\"$::dmailTivoURL/blocklist_addremove/$title\" title=\"Click here to remove this title from your global block list.\" target=\"_blank\">U</a>\n"										
						}
					} else {
						if {$::graphicson} {
							writehtml "</td><td valign=middle class=invisible>&nbsp;<a href=\"$::dmailTivoURL/blocklist_addremove/$title\" title=\"Click here to add this title to your global block list.\" target=\"_blank\"><img src=\"[imageref $::blockmegraphic]\" border=\"0\" title=\"Click here to add this title to your global block list.\" alt=\"B\"></a>\n"	
						} else {
							writehtml "</td><td valign=middle class=invisible>&nbsp;<a href=\"$::dmailTivoURL/blocklist_addremove/$title\" title=\"Click here to add this title to your global block list.\" target=\"_blank\">B</a>\n"										
						}	
					}
				}

				## End of Global Block Extra Functionality function

				writehtml "&nbsp;</td></tr></table>"
				if {$eptitle !=""} {
					if {$descr !=""} {
						writehtml "$eptitle - $descr"
					} else {
						writehtml "$eptitle"
					}
				} else {
					if {$descr !=""} {
						writehtml "$descr"
					} else {
						writehtml "No description."
					}
				}


				if { $airdatestr != "" || $premstr != "" } {
					if { $airdatestr != "" } {
						if { $premstr != "" } {
							writehtml " (${airdatestr} | ${premstr})"
						} else {
							writehtml " (${airdatestr})"
						}			
					} else {
						writehtml " (${premstr})"
					}
				}


				if {$::dmailLinksOn} {
					writehtml "</td><td class=links${rowclassid}>"
					writehtml "<a href=\"$::dmailTivoURL/editprogram/$fsid\" title=\"Click here to edit recording.\" target=\"_blank\">edit recording</a><br>"
					writehtml "<a href=\"$::dmailTivoURL/showing/$showingfsid\" title=\"Click here to view details.\" target=\"_blank\">view details </a><br>"
					writehtml "<a href=\"$::dmailTivoURL/confirmdelete/2/$fsid\" title=\"Click here to delete recording.\" target=\"_blank\">delete recording</a>"
				}	
				writehtml "</td>"	

				## THUMB GRAPHICS
				if {$::graphicson} {
					if {$::viewthumbs} {
						if {$imagef != ""} {
							writehtml "<td class=thumbs${rowclassid}>"
							if {$::tivowebplususer} {
								writehtml "<img src=\"[imageref $imagef]\" title=\"Thumbs are $xthumbtype.\" alt=\"${thumbcount}${thumbtype}\">"	
							} else {
								if {$::dmailLinksOn && $::series1} {
									writehtml "<a href=\"$::dmailTivoURL/thumbs/$seriesfsid\" target=\"_blank\" ><img src=\"[imageref $imagef]\" border=\"0\" title=\"Thumbs are $xthumbtype. Click&nbsp;here&nbsp;to&nbsp;update&nbsp;thumbs.\" alt=\"${thumbcount}${thumbtype}\"></a>"	
								} else {
									writehtml "<img src=\"[imageref $imagef]\" title=\"Thumbs are $xthumbtype.\" alt=\"${thumbcount}${thumbtype}\">"	
								}
							}
							writehtml "</td>"
						} else {
							writehtml "<td class=thumbs${rowclassid}>&nbsp;"			
							writehtml "</td>"
						}
					}
				} else {
					if {$::viewthumbs} {
						if {$imagef != ""} {
							if {$thumbcount > 0} {
								set appendthumbtext "+"
							} else {
								set appendthumbtext ""
							}
							writehtml "<td class=thumbs${rowclassid}>"
							if {$::tivowebplususer} {
								ritehtml "${appendthumbtext}${thumbcount}${thumbtype}"	
							} else {
								if {$::dmailLinksOn && $::series1} {
									writehtml "<a href=\"$::dmailTivoURL/thumbs/$seriesfsid\" target=\"_blank\" title=\"Thumbs are $xthumbtype. Click&nbsp;here&nbsp;to&nbsp;update&nbsp;thumbs.\">${appendthumbtext}${thumbcount}${thumbtype}</a>"	
								} else {
									writehtml "${appendthumbtext}${thumbcount}${thumbtype}"				
								}
							}
							writehtml "</td>"
						} else {
							writehtml "<td class=thumbs${rowclassid}>&nbsp;"			
							writehtml "</td>"
						}
					}			
				}

				## END OF THUMB GRAPHICS

				## MULTI THUMB UPDATE
				if {$::tivowebplususer} {
					## null
				} else {
					if {$::series1} {
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-multi thumb update item"}
						if {$::todomultithumbupdate} {
							if {$::dmailLinksOn} {
								writehtml "<td class=thumbupdate${rowclassid}>"
								set thumbitemmatch 0
								foreach tempitem $progressivethumbs {
									if {"$tempitem"=="$seriesfsid"} {
										set thumbitemmatch 1
									}
								}
								if {$thumbitemmatch==0} {
									set seriesfsidname "seriesfsid_"
									append seriesfsidname $nowshowingcount
									append seriesfsidname "_"
									append seriesfsidname $seriesfsid
									append seriesfsidname "_"
									append seriesfsidname $fsid
									if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-multi thumb update - checkpoint A"}
									writehtml "<select name=$seriesfsidname size=1 style=\"font-size: 8pt; font-family: Arial, sans-serif;\">"
									if {$thumbtype == "E" && $thumbcount == 3} {
										writehtml "<option value=\"N_3\" selected=TRUE>+3</option>"
									} else {
										writehtml "<option value=\"Y_3\">+3</option>"
									}
									if {$thumbtype == "E" && $thumbcount == 2} {
										writehtml "<option value=\"N_2\" selected=TRUE>+2</option>"
									} else {
										writehtml "<option value=\"Y_2\">+2</option>"
									}
									if {$thumbtype == "E" && $thumbcount == 1} {
										writehtml "<option value=\"N_1\" selected=TRUE>+1</option>"
									} else {
										writehtml "<option value=\"Y_1\">+1</option>"
									}
									if {($thumbtype == "E" && $thumbcount == 0) || ($thumbtype == "X")} {
										writehtml "<option value=\"N_0\" selected=TRUE>0</option>"
									} else {
										writehtml "<option value=\"Y_0\">0</option>"
									}
									if {$thumbtype == "E" && $thumbcount == -1} {
										writehtml "<option value=\"N_-1\" selected=TRUE>-1</option>"
									} else {
										writehtml "<option value=\"Y_-1\">-1</option>"
									}
									if {$thumbtype == "E" && $thumbcount == -2} {
										writehtml "<option value=\"N_-2\" selected=TRUE>-2</option>"
									} else {
										writehtml "<option value=\"Y_-2\">-2</option>"
									}
									if {$thumbtype == "E" && $thumbcount == -3} {
										writehtml "<option value=\"N_-3\" selected=TRUE>-3</option>"
									} else {
										writehtml "<option value=\"Y_-3\">-3</option>"
									}
									if {$thumbtype == "I" || $thumbtype == "P"} {
										writehtml "<option value=\"N_-999\"selected=TRUE>-</option>"
									} else {
										writehtml "<option value=\"Y_-999\">-</option>"
									}
									writehtml "</select>"
									if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-multi thumb update - checkpoint B"}
									lappend progressivethumbs "$seriesfsid"
								} else {
									if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-multi thumb update - checkpoint D"}
									if {$::yankspeak} {
										if {$::graphicson} {
											writehtml "<img src=\"[imageref $::multiupdatethumbsblankboxfilename]\" border=\"0\" title=\"Program is in a duplicate series so thumb update option is not required. Update prior item in To Do list.\" alt=\"XXX\">"	
										}
									} else {
										if {$::graphicson} {
											writehtml "<img src=\"[imageref $::multiupdatethumbsblankboxfilename]\" border=\"0\" title=\"Programme is in a duplicate series so thumb update option is not required. Update prior item in To Do list.\" alt=\"XXX\">"	
										}
									}
								}
								writehtml "</td>"
							}
						}
					}
				}
				## END OF MULTI THUMB UPDATE

				## MULTI DELETE CHECKBOXES
				if {$::todomultidelete} {
					if {$::dmailLinksOn} {
						writehtml "<td class=action${rowclassid}>"
						set temptext "fsid_"
						append temptext $nowshowingcount
						append temptext "_"
						append temptext $fsid
						writehtml "<input type=\"checkbox\" name=\"$temptext\" >"
						writehtml "</td>"
					}
				}

				### END OF MULTI DELETE CHECKBOXES

				writehtml "</tr>"

				set nowshowingcount [expr $nowshowingcount + 1]
				set repeatbarcount [expr $repeatbarcount + 1]
			
			}
			
		}
		
		set donecount [expr $donecount + 1]

	}
	
	# clear down variables 	
	foreach var [info vars] {
		catch {
			if {$var != "nowshowingcount"} {
				if { [catch { 
					if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-unsetting variable >>$var<<"}
				} fid] } {
					# null
				} else {
					if { [catch { 
						unset $var  
					} fid] } {
						if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-error in unsetting variable >>$var<<"}
					} 
				}
			}
		}
	}
	
	return $nowshowingcount
	catch { unset nowshowingcount }

}

proc imageref {filename} {
	if { $::embeddedimages } {
		set outputtext "cid:$filename.$::uniquecontentid@$::domain"
	} else {
		set outputtext "$::dmailGraphicsURL/$filename"
	}
	catch {unset filename}
	return $outputtext
	catch {unset outputtext}
}

#####################################################
## Generate To Do List

proc gettodo {hoursahead} {

	if {$::debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-compiling to do list"}

	set itemsFound 0
	set multicomplete 0
	set runningmegused 0
	set path "/Recording/Active"
	set prefix "4"
	set numofitems 0
	set ouritemid 0
	set progressivethumbs "999999999"
	set maxexpirytime 0
	set colourtoggle 1
	
	if {$::yankspeak} {
		set program_word "rogram"
		set organize_word "rganize"
	} else {
		set program_word "rogramme"
		set organize_word "rganise"
	}

	## EXPIRY - SPACE USED CODE

	set expirytime 999
	set expirysize 999
	set expirytitle "XXX"
	set expirytype "XXX"
	set expirycount 0
	set expiryrectime 999

	ForeachMfsFileTrans fsid name type $::nowshowingdir "" 10 {
		catch {
			set rec [db $::db openid $fsid]	
			if {$::version >= 3} {
				set recbeh [dbobj $rec get RecordingBehavior]
				set seltype [dbobj $recbeh get PresentationBehavior]
			} else {
				set seltype [dbobj $rec get SelectionType]
			}

			## IGNORE SELECTION / PRESENTATION ITEM 

			set ignorethisitem "N"
			foreach ignoreitem $::ignorelist {
				if { $ignoreitem ==  $seltype } {
					set ignorethisitem "Y"
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ignore item at user request"}
				}
			}

			##

			set expaddbackinreq false		
			if { $::countexpiredasfreespace } {
				# if we count expired items as free space we will want to add them in when expiry happens
				if { $::countsuggestionsasfreespace } {
					# if suggestions are treat as free space then ...
					if { $seltype != 6 } {
						# if item is not a suggestion then we will want to add back in when expired
						set expaddbackinreq  true
					} else {
						# if item is a suggestion and we treat suggestions as free space then we don't want to add expired suggestions back in as all suggestions are classified free space
					}
				} else {
					# if suggestions are treat as used space then we will want to add them back in when expiry happens
					if {$seltype == 6 && $::expiredsuggestionstreatment == "S"} {
						# except if expired suggestions are still classified as exceptions rather than expired items
					} else {
						set expaddbackinreq true
					}
				}
			} else {
				# if we count expired items as used space then we never want to add them back in when expiry happens
			}
			if {$expaddbackinreq} {
				set expdate [dbobj $rec get ExpirationDate]
				set expsecs [expr $expdate * 86400 + [dbobj $rec get ExpirationTime]]
				if {$expsecs < [expr $hoursahead * 3600 + [clock seconds]] && $expsecs > [clock seconds] } {
					set showing [dbobj $rec get Showing]
					set program [dbobj $showing get Program]
					set title [strim [dbobj $program get Title]]
					set state [dbobj $rec get State]
					set startdate [dbobj $rec get StartDate]
					set starttime 0
					set starttime [dbobj $rec get StartTime]
					if { $starttime == "" } {
						set starttime [dbobj $showing get Time]
					}
					if {$starttime == ""} {
						set starttime 0
					}
					set rectime [expr $startdate * 86400 + $starttime]
					if { [catch {dbobj $rec get StreamFileSize} streamsize] } { set streamsize 0 }
					if { $streamsize == "" } { set streamsize 0 }
					set parts [dbobj $rec get Part]
					set recquality [dbobj $rec get RecordQuality]
					if { ($streamsize == 0) && ($state == 3 || $parts == "") } {
						switch -exact $recquality {
							0	{ set bitrate [expr $::uktivo ? 1700000 : 1630000] }
							40	{ set bitrate 2760000 }
							75	{ set bitrate 3660000 }
							default	{ set bitrate 5960000 }
						}
						set seconds [dbobj $showing get Duration]
						set minutes [expr $seconds / 60]
						set size [expr ($seconds * ($bitrate / (8 * 1024))) / 1024]
					} else {
						set size 0
						if { $streamsize == 0 } {
							foreach part $parts {
								set file [dbobj $part get File]
								if { [catch {mfs streamsize $file} sizes] } {
								} else {
									incr size [expr ([lindex $sizes 0] / 1024) * [lindex $sizes 1] / 1024]
								}
							}
						} else {
							set size [expr $streamsize / 1024]
						}
					}	
					if {$ignorethisitem == "Y"} {
						set title "Other Item"
					}
					lappend expirytime $expsecs
					lappend expirysize [expr $size * 1.0000]
					lappend expirytitle $title
					lappend expirytype "PRECURSOR"
					lappend expiryrectime $rectime
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-exiry item added : expirytime >>$expsecs<< : expirysize >>[expr $size * 1.0000]<< : expirytitle >>$title<< : expirytype >>PRECURSOR<< : expiryrectime >>$rectime<<"}
					set expirycount [expr $expirycount + 1]
				}
			}
		}
	}
	catch { unset rec }

	##

	## TRACKER SETUP CODE

	if {$::trackerblockreq} {

		## read tracker config file code from sandertons tracker module

		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-TRACKER CONFIG - start"}
		
		  set lastupdate ""
		  set blockwatchedID ""
		  set blockunwatchedID ""
		  set blockwatchedTD ""
		  set blockunwatchedTD ""
  		  set ignoregenerics ""
  
		set configtrk [open $::trackerdir/tracker.cfg r]
		set settings [read $configtrk]
		close $configtrk
		eval $settings
  
  		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-TRACKER CONFIG - lastupdate >>$lastupdate<<"}
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-TRACKER CONFIG - blockwatchedID >>$blockwatchedID<<"}
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-TRACKER CONFIG - blockunwatchedID >>$blockunwatchedID<<"}
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-TRACKER CONFIG - blockwatchedTD >>$blockwatchedTD<<"}
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-TRACKER CONFIG - blockunwatchedTD >>$blockunwatchedTD<<"}
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-TRACKER CONFIG - ignoregenerics >>$ignoregenerics<<"}
		
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-TRACKER CONFIG - end"}
			

		## end tracker config file code from sandertons tracker module

		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-start tracker block list setup"}

		## block list setup from sandertons tracker module

		set blocklist {}
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-TRACKER CONFIG - trackerdir >>$$::trackerdir<<"}
		if {$blockwatchedID == 1} {
			if { [catch {
			    if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-TRACKER CONFIG - block_WU - A"}
			    set openfile [open $::trackerdir/block_WU r]
			    if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-TRACKER CONFIG - block_WU - B"}
			    set blockadd [read $openfile]
			    if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-TRACKER CONFIG - block_WU - C"}
			    close $openfile
			    if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-TRACKER CONFIG - block_WU - D"}
			    set blocklist [concat $blocklist $blockadd]
			    if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-successfully queried block_WU file"}
			} ] } { 
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ERROR - could not open block_WU file"}
			}
		}
		if {$blockunwatchedID == 1} {
			if { [catch {
			    set openfile [open $::trackerdir/block_UU r]
			    set blockadd [read $openfile]
			    close $openfile
			    set blocklist [concat $blocklist $blockadd]
			    if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-successfully queried block_UU file"}
			} ] } { 
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ERROR - could not open block_UU file"}
			}
		}
		if {$blockwatchedTD == 1} {
			if { [catch {
			    set openfile [open $::trackerdir/block_WT r]
			    set blockadd [read $openfile]
			    close $openfile
			    set blocklist [concat $blocklist $blockadd]
			    if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-successfully queried block_WT file"}
			} ] } { 
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ERROR - could not open block_WT file"}
			}
		}
		if {$blockunwatchedTD == 1} {
			if { [catch {
			    set openfile [open $::trackerdir/block_UT r]
			    set blockadd [read $openfile]
			    close $openfile
			    set blocklist [concat $blocklist $blockadd]
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-successfully queried block_UT file"}
			} ] } { 
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ERROR - could not open block_UT file"}
			}
		}
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-block list >>$blocklist<<"}

		## end block list setup from sandertons tracker module
		
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ended tracker block list setup"}
	}
	
	## END TRACKER SETUP CODE
	
	## GLOBAL BLOCKLIST SETUP CODE
	
	if {$::globalblockreq} {
	
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-start global block list setup"}
	
		proc gbl_load {filename} {
			if {![file exists $filename]} {
				set openfile [open $filename w]
				close $openfile
			}
			set openfile [open $filename r]
			set ret [read $openfile]
			close $openfile
			return $ret
		}

		proc gbl_andlogic {element description} {
			set ret $element
			while {[string match "*+*" $element] == 1} {
				set sliceright [string first "+" $element]
				set sliceleft [expr {$sliceright - 1}]
				incr sliceright
				set stringbit [string range $element 0 $sliceleft]
				set element [string range $element $sliceright end]
				if {[string match [string tolower *$stringbit*] [string tolower $description]] == 0} {
					set ret 0
				}		
			}
			if {[string match [string tolower *$element*] [string tolower $description]] == 0} {
				set ret 0
			}	
			return $ret
		}

		set globalblocklist [gbl_load "/var/hack/blocklist.txt"]
		set globalblockpatt [gbl_load "/var/hack/blockpatt.txt"]
		
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-end global block list setup"}
		
	}
	
	## END GLOBAL BLOCKLIST SETUP CODE

	## ENDPAD SETUP

	if { $::endpadinstalled && $::endpadstatus && $::endpadtodoliston} {

		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-need to look for overlapping programs with endpad"}

		## endpad pre-check

		set endpadstarttimes 0
		set endpadendtimes 0
		set endpadrectype "Dummy"
		set endpadrecstatus "Dummy"
		set norecordmessage "Dummy"
		set frontpadding 0
		set backpadding 0

		after 2000

		ForeachMfsFileTrans fsid name type $path $prefix 10 {

			set rec [db $::db openid $fsid]
			set showing [dbobj $rec get Showing]
			set starttime [expr [dbobj $showing get Date] * 86400 + [dbobj $showing get Time]]

			if {$starttime <= [expr ($hoursahead *3600) + [clock seconds]]} {
				set duration [dbobj $showing get Duration]
				set endtime [expr $starttime + $::tzoffset + $duration]
				set starttime [expr $starttime + $::tzoffset]		
				if {$::version >= 3} {
					set recbeh [dbobj $rec get RecordingBehavior]
					set seltype [dbobj $recbeh get PresentationBehavior]
				} else {
					set seltype [dbobj $rec get SelectionType]
				}
				if { ( $::version >= 3 && $seltype != 8 ) || $::version < 3 } {
					if {$seltype == 6} {
						lappend endpadrectype "Suggestion"
					} else {
						lappend endpadrectype "Other"
					}
					lappend endpadstarttimes "$starttime"
					lappend endpadendtimes "$endtime"
					set numofitems [ expr $numofitems + 1 ]
				} else {
					if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ignored item - invisible"}
					# type 8 items not added to count - whereas other user defined ignore items are
				}

			}
			catch { unset rec }
		}
						
		set currentcount 1
		set endpadrecstatus "Dummy"
		set runningmessage ""

		## check overlaps

		while { $currentcount <= $numofitems } {
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]--------------------------------------"}
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-item: >>$currentcount<<"}
			set currentitemrecord true
			set runningmessage ""
			set thisbackpadding 0
			set thisfrontpadding 0
			
			## default padding allocation
			
			set totalrequiredpadmin [expr $::endpadendpadmin + $::endpadstartpadmin ]
			if {$currentcount != 1} {
				set oursecondsdifffront [expr [lindex $endpadstarttimes $currentcount] - [lindex $endpadendtimes [expr $currentcount - 1]]]
				set ourminutesdifffront [expr round($oursecondsdifffront / 60.0)]
			}
			set oursecondsdiffback [expr [lindex $endpadstarttimes [expr $currentcount + 1]] - [lindex $endpadendtimes $currentcount]]
			set ourminutesdiffback [expr round($oursecondsdiffback / 60.0)]
			
			if {$currentcount == 1} {
				set thisfrontpadding $::endpadstartpadmin	
				if {$ourminutesdiffback >= $::endpadendpadmin} {
					set thisbackpadding $::endpadendpadmin
					set anybackremainder [expr $ourminutesdiffback - $::endpadendpadmin]
				} else {
					set thisbackpadding $ourminutesdiffback
					set anybackremainder 0
				}
			} elseif {$currentcount == $numofitems} {
				if {$anybackremainder >= $::endpadstartpadmin} {
					set thisfrontpadding $::endpadstartpadmin	
				} else {
					set thisfrontpadding $anybackremainder 
				}
				set thisbackpadding $::endpadendpadmin	
			} else {
				if {$anybackremainder >= $::endpadstartpadmin} {
					set thisfrontpadding $::endpadstartpadmin	
				} else {
					set thisfrontpadding $anybackremainder 
				}
				set anybackremainder 0
				if {$ourminutesdiffback >= $::endpadendpadmin} {
					set thisbackpadding $::endpadendpadmin
					set anybackremainder [expr $ourminutesdiffback - $::endpadendpadmin]
				} else {
					set thisbackpadding $ourminutesdiffback
					set anybackremainder 0
				}
			}
	
			## end default padding allocation

			## endpadplus makes both suggestions + recordings equal so nothing will ever be cancelled

			if {$::everythingeq} {
				# do nothings - everything is equal
			} else {

				# now we need to check that this programme is not a suggestion and the beginning would be overlapped by a previous non suggestion ...

				if { $currentcount != 1 && $currentitemrecord} {
				
					# if this is not the first program in the list and we are currently intending to record this item
					if { [ lindex $endpadrectype $currentcount ] == "Suggestion" && [ lindex $endpadrectype [ expr $currentcount - 1 ] ] == "Other" } {
						# if this program is a suggestion and the previous program is not a suggestion
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-check start time overlap"}
						if { [ lindex $endpadstarttimes $currentcount ] < [ expr [ lindex $endpadendtimes [ expr $currentcount - 1 ] ] + [ expr $::endpadendpadmin * 60 ] ] } {
							# if there is an overlap - suggestion canned
							set currentitemrecord false
							if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-there is an overlap -> this programme will probably not be recorded"}
							set runningmessage "Adding&nbsp;end-padding&nbsp;to&nbsp;the&nbsp;previous&nbsp;recording will&nbsp;cause&nbsp;this&nbsp;suggestion&nbsp;to&nbsp;be&nbsp;cancelled."
						} else {
							if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-there is no overlap"}
						}
					}
				}

				## now we need to check that this programme is not a suggestion and the beginning would be overlapped by a previous suggestion that is recording

				if { $currentcount != 1 && $currentitemrecord && [ strim [ lindex $endpadrecstatus [ expr $currentcount - 1 ] ] ] != "NoRecord"} {
					# if this is not the first program in the list and the previous item is expected to be recorded
					if { [ lindex $endpadrectype $currentcount ] == "Suggestion" && [ lindex $endpadrectype [ expr $currentcount - 1 ] ] == "Suggestion" } {
						# if the current program is a suggestion and previous type is a suggestion
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-check start time overlap for back-to-back suggestions"}

						## updated endpad provides suggestion equalisation functions - only run next code if equalisation not active / available

						if { $::suggestioneq } {
							# null
							if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-suggestion equalisation is on - back-to-back suggestions allowed"}
						} else {
							# if suggestions not equal
							if { [ lindex $endpadstarttimes $currentcount ] < [ expr [ lindex $endpadendtimes [ expr $currentcount - 1 ] ] + [ expr $::endpadendpadmin * 60 ] ] } {
								# if there is an overlap
								set currentitemrecord false
								if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-there is an overlap -> this programme will probably not be recorded"}
								set runningmessage "Adding&nbsp;end-padding&nbsp;to&nbsp;the&nbsp;previous&nbsp;suggestion will&nbsp;cause&nbsp;this&nbsp;suggestion&nbsp;to&nbsp;be&nbsp;cancelled."
							} else {
								if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-there is no overlap"}
							}
						}
					}
				} 
			}
			if { $currentitemrecord } {
				lappend endpadrecstatus "Record"
				lappend norecordmessage "x"
			} else {
				lappend endpadrecstatus "NoRecord"
				lappend norecordmessage "$runningmessage"
				set thisbackpadding 0
				set thisfrontpadding 0
			}
			
			if { ([lindex $endpadrecstatus [expr $currentcount - 1 ] ] == "NoRecord") && ($currentcount != 1)} {
				set thisfrontpadding $::endpadstartpadmin
			}
			
			if {$thisfrontpadding < 0} {set thisfrontpadding 0}
			if {$thisbackpadding < 0} {set thisbackpadding 0}
			
			## recording padding details
			
			lappend frontpadding $thisfrontpadding
			lappend backpadding $thisbackpadding
			
			##
			
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-item status : >>[lindex $endpadrecstatus $currentcount]<< | front padding : >>[lindex $frontpadding $currentcount]<< | back padding : >>[lindex $backpadding $currentcount]<<"}

			set currentcount [ expr $currentcount + 1 ]
		}
		
		## just making sure that if any items are not recording then the preceding item will have full back padding
		set currentcount 1
		set newbackpadding 0
		while { $currentcount <= $numofitems } {
		
			if { ( [lindex $endpadrecstatus [expr $currentcount + 1 ] ] == "NoRecord" ) && ( $currentcount != $numofitems ) } {
				lappend newbackpadding $::endpadendpadmin
			} else {
				lappend newbackpadding [ lindex $backpadding $currentcount ]
			}
			set currentcount [ expr $currentcount + 1 ]
			
		} 
		set backpadding $newbackpadding
		
		##
		
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-front padding list >>$frontpadding<< | back padding list >>$backpadding<<"}

	}
	
	## END ENDPAD SETUP

	## MAIN LOOP

	if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-starting main to-do loop"}
	set currentcount 1
	set oldday ""

	after 2000
	
	ForeachMfsFileTrans fsid name type $path $prefix 10 {

		set rec [db $::db openid $fsid]
		set showing [dbobj $rec get Showing]
		set starttime [expr [dbobj $showing get Date] * 86400 + [dbobj $showing get Time]]
		set futurestarttime $starttime
		if {$::version >= 3} {
			set recbeh [dbobj $rec get RecordingBehavior]
			set seltype [dbobj $recbeh get PresentationBehavior]
		} else {
			set seltype [dbobj $rec get SelectionType]
		}

		if {$starttime <= [expr ($hoursahead *3600) + [clock seconds]]} {
				
			if {$::debuglvl>2} { puts "---------- new programme - check point #1"}
		
			## IGNORE SELECTION / PRESENTATION ITEM 
			set ignorethisitem "N"
			foreach ignoreitem $::ignorelist {
				if { $ignoreitem ==  $seltype } {
					set ignorethisitem "Y"
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ignore item at user request"}
				}
			}
			
			##
				
			## we want to ignore INVISIBLE program types as they just cause trouble and are not real programs but other data
			if { ( $::version >= 3 && $seltype != 8 ) || $::version < 3 } {

				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-within to-do loop - check point #2"}
				if {$ignorethisitem == "N"} {
			
					set itemsFound 1
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-within to-do loop - check point #3"}
					set showingfsid [dbobj $rec gettarget Showing]
					set station [dbobj $showing get Station]
					set stationfsid [dbobj $station fsid]
					set callsign [dbobj $station get CallSign]
					set program [dbobj $showing get Program]
					set title [strim [dbobj $program get Title]]
					set descr [strim [dbobj $program get Description]]
					set durationhours [clock format [dbobj $showing get Duration] -format "%H"]
					set durationminutes [clock format [dbobj $showing get Duration] -format "%M"]
					set duration [dbobj $showing get Duration]
					set series [dbobj $program get Series]
					set seriesfsid [dbobj $series fsid]
					if {[dbobj $program get OriginalAirDate] == [dbobj $showing get Date]} {
						set newepisode true
					} else {
						set newepisode false
					}

					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-program >>$program<< | title >>$title<<"}
			
					if {$series != ""} {
						set episodic [defaultval 1 [dbobj $series get Episodic]]
					} else {
						set episodic 1
					}
					if { $episodic == 1 } {
						set eptitle [strim [dbobj $program get EpisodeTitle]]
						if { $eptitle == "" } {
							set eptitle "No Episode Title"
						}
					} else {
						set eptitle ""
					}
					
					set blockthis ""
					set globalblock ""
					
					## code from tracker by sanderton

					if {$::trackerblockreq} {
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-tracker blocker start"}
						set tmsid [dbobj $program get TmsId]
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-tmsid >>$tmsid<<"}
					      	set ismatch [lsearch -exact $blocklist $tmsid]
					      	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ismatch >>$ismatch<<"}
					      	set isgeneric [string match ????????0000 $tmsid]
					      	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-isgeneric >>$isgeneric<<"}
					      	if {$ismatch >= 0} {set blockthis "Yes"}
					      	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ignoregenerics >>$ignoregenerics<<"}
					      	if {$isgeneric == 1 && $ignoregenerics == 1} {set blockthis ""}
						if {$blockthis == "Yes"} {
							if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-tracker blocker - item will be marked"}
						} else {
							if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-tracker blocker - item will NOT be marked"}
						}
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-tracker blocker end"}
					}
					
					## end of code from tracker by sanderton
					
					## Global blocklist functionality
					
					if {$::globalblockreq} {
					
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-global blocker start"}
						
						set pattmatch 0
						set andmatch 0
						foreach element $globalblockpatt {
							if {[string match "*+*" $element]} {
								set andmatch [gbl_andlogic $element $eptitle$descr]
								if {$andmatch != 0} {
									set pattmatch $andmatch
								}
							} elseif {[string match [string tolower *$element*] [string tolower $eptitle$descr]] == 1} {
								set pattmatch $element
							}
						}
						if {[lsearch [string tolower $globalblocklist] [string tolower $title]] >= 0} {
							# match with title
							set blockthis "Yes"
							set globalblock "Yes"
							if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-global blocker - item will be marked #1"}
						} elseif {$pattmatch != 0} {
							# match with pattern
							set blockthis "Yes"
							set globalblock "Yes"
							if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-global blocker - item will be marked #2"}
						} else {
							# no match with pattern
							# do nothing
						}
						
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-global blocker end"}
					}
					
					## End of global blocklist functionality
					
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-within to-do loop - check point #4"}
					if {$::yankspeak} {
						set nowday [clock format [expr $starttime + $::tzoffset - $::listseperatoroffset] -format {%A, %B %d}]
					} else {
						set nowday [clock format [expr $starttime + $::tzoffset - $::listseperatoroffset] -format {%a, %d %b}]
					}
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-within to-do loop - check point #5"}

					if {[clock format [expr $starttime + $::tzoffset + $duration] -format {%a}] == [clock format [expr $starttime + $::tzoffset] -format {%a}]} {
						# start day and end day the same 
						if {$::yankspeak} {
							set endtime [clock format [expr $starttime + $::tzoffset + $duration] -format {%I:%M%p}]
							set starttime [clock format [expr $starttime + $::tzoffset] -format {%a %I:%M%p}]
						} else {
							set endtime [clock format [expr $starttime + $::tzoffset + $duration] -format {%H:%M}]
							set starttime [clock format [expr $starttime + $::tzoffset] -format {%a %H:%M}]
						}
					} else {
						# start day and end day different
						if {$::yankspeak} {
							set endtime [clock format [expr $starttime + $::tzoffset + $duration] -format {%a %I:%M%p}]
							set starttime [clock format [expr $starttime + $::tzoffset] -format {%a %I:%M%p}]
						} else {
							set endtime [clock format [expr $starttime + $::tzoffset + $duration] -format {%a %H:%M}]
							set starttime [clock format [expr $starttime + $::tzoffset] -format {%a %H:%M}]
						}
					}
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-within to-do loop - check point #6"}

					## INITIAL THUMBS SETUP

					set seriesfsid ""
					set thumbs ""
					set imagef ""
					set thumbcount 0
					set thumbtype ""
					set xthumbtype ""
					set series [dbobj $program get Series]
					if {$::viewthumbs || $::todomultithumbupdate} {
						if { $series != "" } {
							if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-calculating thumbs"}   
							set seriesfsid [dbobj $series fsid]
							set score [dbobj $series get ThumbData]
							if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-score >>$score<<"}   
							if { $score != "" } {
								set thumbdata [ReadableThumbs $score]
								if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-thumb data >>$thumbdata<<"}   
								scan $thumbdata "%s %d %d" thumbtype numthumbs thumbconf
								if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-thumbtype >>$thumbtype<< | numthumbs >>$numthumbs<< | thumbconf >>$thumbconf<<"} 
								if {$thumbtype == "Predicted"} {
									switch -- $numthumbs {
										3	{set imagef "$::predictedthreethumbupgraphic" }
										2	{set imagef "$::predictedtwothumbupgraphic" }
										1	{set imagef "$::predictedonethumbupgraphic"  }
										0	{set imagef ""}
										-1	{set imagef "$::predictedonethumbdowngraphic" }
										-2	{set imagef "$::predictedtwothumbdowngraphic" }
										-3	{set imagef "$::predictedthreethumbdowngraphic" }
										default {set imagef ""}
									}
									set thumbtype "P"
									set thumbcount $numthumbs
									set xthumbtype "Predicted"
								} elseif {$thumbtype=="Explicit"} {
									switch -- $numthumbs {
										3	{set imagef "$::explicitthreethumbupgraphic" }
										2	{set imagef "$::explicittwothumbupgraphic" }
										1	{set imagef "$::explicitonethumbupgraphic"  }
										0	{set imagef ""}
										-1	{set imagef "$::explicitonethumbdowngraphic" }
										-2	{set imagef "$::explicittwothumbdowngraphic" }
										-3	{set imagef "$::explicitthreethumbdowngraphic" }
										default {set imagef ""}
									}
									set thumbtype "E"
									set thumbcount $numthumbs
									set xthumbtype "Explicit"
								} elseif {$thumbtype=="Implicit" || $thumbtype=="Implied"} {
									switch -- $numthumbs {
										3	{set imagef "$::impliedthreethumbupgraphic" }
										2	{set imagef "$::impliedtwothumbupgraphic" }
										1	{set imagef "$::impliedonethumbupgraphic" }
										0	{set imagef "" }
										-1	{set imagef "$::impliedonethumbdowngraphic" }
										-2	{set imagef "$::impliedtwothumbdowngraphic" }
										-3	{set imagef "$::impliedthreethumbdowngraphic" }
										default {set imagef ""}
									}
									set thumbtype "I"
									set thumbcount $numthumbs
									set xthumbtype "Implied"
								} else {
									set thumbtype "I"
									set thumbcount 0
									set imagef $::unsetthumbsgraphic
									set xthumbtype "Implied"
								}
								if {$imagef=="" } {
									set imagef $::unsetthumbsgraphic
								}
								if {$thumbtype==""} {
									set thumbtype "I"
									set xthumbtype "Implied"
								}
								if {$numthumbs==""} {
									set numthumbs 0
								}
								if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-thumb image >>$imagef<< | thumb count >>$thumbcount<< | thumb type >>$thumbtype<< | expanded thumb type >>$xthumbtype<<"}   
							} else {
								set imagef $::unsetthumbsgraphic
								set thumbtype "I"
								set numthumbs 0
								set xthumbtype "Implied"							
							}
						}
					}

					## END OF INITIAL THUMB SETUP
					
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-within to-do loop - check point #9"}

					## Main HTML Generation 

					if {$seltype != 6 || $::dmailShowSuggestions} {

						## Start blank date row insert

						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-within to-do loop - blank row insert"}
						if {$::listseperator} {
							if {$oldday != $nowday} {
								writehtml "<tr><td class=seperator>$nowday</td>"
								if {$::dmailLinksOn} {
									writehtml "<td class=links>&nbsp;</td>"				
								}
								if {$::viewthumbs} {
									writehtml "<td class=thumbs>&nbsp;</td>"			
								}
								## for multi-thumb update
								if {$::multirepeat || $multicomplete==0} {
									if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-multi thumb update header start"}
									if {$::tivowebplususer} {
										## null
									} else {
										if {$::series1} {
											if {$::todomultithumbupdate} {
												if {$::dmailLinksOn} {
													if {$::graphicson} {
														writehtml "<td class=thumbupdate><input type=\"image\" src=\"[imageref $::multiupdatethumbsfilename]\" value=\"Submit\" name=\"ThumbUpdate_ToDo\" title=\"Update thumb settings for p${program_word}s in the to do list.\" alt=\"Update\"></a></td>"
													} else {
														writehtml "<td class=thumbupdate><center><input type=\"submit\" Name=\"ThumbUpdate_ToDo\" value=\"update\" style=\"height: 22px; font-size: 8pt; width: 50px;\"></center></td>"	           	
													}
												}
											}
										}
									}
									if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-multi thumb update header end"}
									if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-multi delete header start"}
									### for checkbox action items
									if {$::todomultidelete} {
										if {$::dmailLinksOn} {
											if {$::graphicson} {
												writehtml "<td class=action><input type=\"image\" src=\"[imageref $::mutideletefilename]\" value=\"Submit\" name=\"Delete_ToDo\" title=\"Delete selected p${program_word}s from the to do list.\" alt=\"Delete\"></a></td>"
											} else {
												writehtml "<td class=action><center><input type=\"submit\" Name=\"Delete_ToDo\" value=\"del\" style=\"height: 22px; font-size: 8pt; width: 36px;\"></center></td>"
											}
										}
									}
									if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-multi delete header end"}
									set multicomplete 1
								} else {
									if {$::todomultithumbupdate} {
										writehtml "<td class=thumbupdate>&nbsp;</td>"
									}
									if {$::todomultidelete} {
										writehtml "<td class=action>&nbsp;</td>"
									}
								}
								writehtml "</tr>"			
								set oldday $nowday
							}
						}
						### End of blank date row insert
						
						## Main Program Row Insert
						
						if {$::multicolourbar} {
							set rowclassid "$colourtoggle"
							if {$colourtoggle == 1} {
								set colourtoggle 2
							} else {
								set colourtoggle 1
							}
						} else {
							set rowclassid ""
						}

						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-within to-do loop - check point #10"}
						if {$seltype == 6} {
							if { $::endpadinstalled && $::endpadstatus && $::endpadtodoliston} {
								if { [ strim [ lindex $endpadrecstatus $currentcount ] ] == "NoRecord" } {
									writehtml "<tr><td class=suggestion>"
								} else {
									if { ( $::trackerblockreq  || $::globalblockreq ) && $blockthis=="Yes"} {
										writehtml "<tr><td class=blockedprogramme>"
										set ::alertstatus true
										append ::alertreasons "Blocked Program - "
									} else {
										writehtml "<tr><td class=programme${rowclassid}>"
									}
								}
							} else {
								if { ( $::trackerblockreq  || $::globalblockreq ) && $blockthis=="Yes"} {
									writehtml "<tr><td class=blockedprogramme>"
									set ::alertstatus true
									append ::alertreasons "Blocked Program - "
								} else {
									writehtml "<tr><td class=programme${rowclassid}>"
								}
							}
						} else {
							if { ( $::trackerblockreq  || $::globalblockreq ) && $blockthis=="Yes"} {
								writehtml "<tr><td class=blockedprogramme>"
								set ::alertstatus true
								append ::alertreasons "Blocked Program - "
							} else {
								writehtml "<tr><td class=programme${rowclassid}>"
							}
						}
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-within to-do loop - check point #11"}
						writehtml "<table border=0 cellspacing=0 cellpadding=0><tr><td valign=middle class=invisible><strong>"
						writehtml "$title" 
						writehtml "</strong> "

						## SPACE CALCULATIONS

						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-start size calc"}
						set state [dbobj $rec get State]
						if { [catch {dbobj $rec get StreamFileSize} streamsize] } { set streamsize 0 }
						if { $streamsize == "" } { set streamsize 0 }
						set parts [dbobj $rec get Part]
						set recquality [dbobj $rec get RecordQuality]
						if { ($streamsize == 0) && ($state == 3 || $parts == "") } {
							switch -exact $recquality {
								0	{ set bitrate [expr $::uktivo ? 1700000 : 1630000] }
								40	{ set bitrate 2760000 }
								75	{ set bitrate 3660000 }
								default	{ set bitrate 5960000 }
							}
							set seconds [dbobj $showing get Duration]
							if { $::endpadinstalled && $::endpadstatus && $::endpadtodoliston} {
								set seconds [expr ([lindex $frontpadding $currentcount] * 60) + ([lindex $backpadding $currentcount] * 60) + $seconds]
							} 
							set minutes [expr $seconds / 60]
							set size [expr ($seconds * ($bitrate / (8 * 1024))) / 1024]
						} else {
							if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-multiple parts"}
							set size 0
							if { $streamsize == 0 } {
								foreach part $parts {
									set file [dbobj $part get File]
									if { [catch {mfs streamsize $file} sizes] } {
										# null
									} else {
										incr size [expr ([lindex $sizes 0] / 1024) * [lindex $sizes 1] / 1024]
									}
								}
							} else {
								set size [expr $streamsize / 1024]
							}
						}
						
						## add TiVo specific varience to size
						set size [expr round((($size * 1.00000) * ($::spacevariance / 100.00000)) + $size)]
						set needtoaddthisspace false
						if { $::countsuggestionsasfreespace } {
							# if suggestions are treat as free space then ...
							if { $seltype != 6 } {
								# if item is not a suggestion then we will want to add space
								set needtoaddthisspace  true
							} else {
								# if item is a suggestion and we treat suggestions as free space then we don't want to add space
							}
						} else {
							# if suggestions are treat as used space then we will want to add the space
							set needtoaddthisspace  true
						}

						if { $::endpadinstalled && $::endpadstatus && $::endpadtodoliston} {
							if { [ strim [ lindex $endpadrecstatus $currentcount ] ] == "NoRecord" } {
								set needtoaddthisspace  false
							}
						}

						if { $needtoaddthisspace } {
							set runningmegused [expr $runningmegused + $size]
						}
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-expiry addition section"}

						## expiry - add back space - if program expires add back space to total available
						set addbacktext ""
						if {$::countexpiredasfreespace} {
							##only add back space if we are treating expired as free space
							set expirycount 0
							set tempmaxexpirytime 0
							foreach ourexpirytime $expirytime {
								if {$ourexpirytime != 999 && $ourexpirytime > $maxexpirytime} {	
									# if the expiry date of item is after the start time of the programme then apply then
									if {$ourexpirytime > [expr [dbobj $showing get Date] * 86400 + [dbobj $showing get Time] ]} {
										# do nothing
									} else {
										set runningmegused [expr $runningmegused - [lindex $expirysize $expirycount]]
										if {$ourexpirytime > $tempmaxexpirytime} {
											set tempmaxexpirytime $ourexpirytime
										}
										set ourTitle [lindex $expirytitle $expirycount]
										set ourType [lindex $expirytype $expirycount]
										set ourSize [lindex $expirysize $expirycount]
										if {$::yankspeak} {
											set ourextratempstarttime [clock format [expr [lindex $expiryrectime $expirycount] + $::tzoffset] -format {%A, %B %d %I:%M%p}]
										} else {
											set ourextratempstarttime [clock format [expr [lindex $expiryrectime $expirycount] + $::tzoffset] -format {%a, %d %b %H:%M}]
										}
										append addbacktext "\n-&nbsp;${ourTitle}&nbsp;(Recorded: &nbsp;${ourextratempstarttime})&nbsp;-&nbsp;[expr round($ourSize)]&nbsp;MB"
										if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-item added back - ${ourType} - ${ourTitle} - Size: ${ourSize}" }
									}
								}
								set expirycount [expr $expirycount + 1]
							}
							if {$tempmaxexpirytime != 0} {
								set maxexpirytime $tempmaxexpirytime
							}
						}
						if {$::showspaceaddedbackicon} {
							if {$addbacktext != ""} {
								set addbacktext "Space&nbsp;added&nbsp;back&nbsp;due&nbsp;to&nbsp;items&nbsp;expiring:${addbacktext}"
								set addbackicon "&nbsp;<img src=\"[imageref $::spaceaddedbackfilename]\" border=\"0\" title=\"${addbacktext}\" alt=\"+\"></td><td valign=middle class=invisible>"
								set addbacktext ""
							} else {
								set addbacktext ""
								set addbackicon ""
							}
						} else {
							set addbacktext ""
							set addbackicon ""
						}

						## end of expiry add back space
						
						## expired and suggestions need to be removed

						if {$::deleteforroomicon} {
							if {[expr $::actualspaceusedmeg+$runningmegused+$::otherspacemeg] >= $::actualdrivespacemeg} {
								if {($::otherspacemeg > 0) && ([expr $::corespaceusedmeg+$runningmegused] <= $::actualdrivespacemeg)} {
									set otherprogremovaladdbackicon "&nbsp;<img src=\"[imageref $::deleteforroomfilename]\" border=\"0\" title=\"Expired items & suggestions will be deleted to make space for this p${program_word}!\" alt=\"-\"></td><td valign=middle class=invisible>"
								} else {
									set otherprogremovaladdbackicon ""
								}
							} else {
								set otherprogremovaladdbackicon ""
							}
						} else {
							set otherprogremovaladdbackicon ""
						}

						## end of exp and sugg need to be removed
						
						## expiry add to list - to check if any of these items expire during the list duration
						set expdate ""
						set expsecs 0
						set expaddbackinreq false
						if { $::countexpiredasfreespace } {
							# if we count expired items as free space we will want to add them in when expiry happens
							if { $::countsuggestionsasfreespace } {
								# if suggestions are treat as free space then ...
								if { $seltype != 6 } {
									# if item is not a suggestion then we will want to add back in when expired
									set expaddbackinreq  true
								} else {
									# if item is a suggestion and we treat suggestions as free space then we don't want to add expired suggestions back in as all suggestions are classified free space
								}
							} else {
								# if suggestions are treat as used space then we will want to add them back in when expiry happens
								if {$seltype == 6 && $::expiredsuggestionstreatment == "S"} {
									# except if expired suggestions are still classified as exceptions rather than expired items
								} else {
									set expaddbackinreq true
								}
							}
						} else {
							# if we count expired items as used space then we never want to add them back in when expiry happens
						}
						if {$expaddbackinreq} {
							set expdate [dbobj $rec get ExpirationDate]
							set expsecs [expr $expdate * 86400 + [dbobj $rec get ExpirationTime]]
							catch {
								if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-expiration date of this program is >>[clock format [expr $expsecs + $::tzoffset] -format {%a, %d %b %Y - %H:%M}]<<"}
							}
							if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-expiration value for program >>$expsecs<<"}
							if { $expsecs != 0 || $expsecs != ""} {
								lappend expirytime $expsecs
								lappend expirysize $size
								lappend expirytitle $title
								lappend expirytype "CURRENT"
								lappend expiryrectime $futurestarttime
								if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-added expiration date item for this program"}
								if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-exiry item added : expirytime >>$expsecs<< : expirysize >>$size<< : expirytitle >>$title<< : expirytype >>CURRENT<< : expiryrectime >>$futurestarttime<<"}
							}
						}
						## end of expiry add to list
						
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-to do running amount proposed used >>$runningmegused<< megabytes"}
						set runningpercentused [expr ((($::actualspaceusedmeg+$runningmegused)*1.0000) / ($::actualdrivespacemeg*1.0000)) * 100.0]
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-running percent used >>$runningpercentused<< %"}
						set remainingspace [expr ($::actualdrivespacemeg - $runningmegused - $::actualspaceusedmeg) * 1]
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-remaining space after prog >>$remainingspace<< megabytes"}
						set percentusedafterprogtemp [expr ((($::actualspaceusedmeg+$runningmegused)*1.0000) / ($::actualdrivespacemeg*1.0000)) * 100.0 ]
						set percentusedafterprog [expr round($percentusedafterprogtemp * 10) / 10.0]
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-percent used after prog >>$percentusedafterprogtemp<< %"}


						## END OF SPACE CALCULATIONS
						
						## REMAINING TIME CALCULATION
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-remaining time calc start"}
						set ourremainingtimetext ""
						if { $::progstatustimeremainingreq } {
							if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-remaining time calc required"}
							set ourremainingspacemeg 0
							set ourremainingspacemeg [expr ($::actualdrivespacemeg - $runningmegused) - $::actualspaceusedmeg]
							if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-remaining space meg >>$ourremainingspacemeg<<"}
							set bitrate 5960000
							switch $::remainingtimeunits {
								"BEST"		{ set bitrate 5960000 }
								"HIGH"		{ set bitrate 3660000 }
								"MEDIUM"	{ set bitrate 2760000 }
								"BASIC"		{ set bitrate [expr $::uktivo ? 1700000 : 1630000] }
								default		{ set bitrate 5960000 }
							}
							set ourUnitsText ""
							switch $::remainingtimeunits {
								"BEST"		{ set ourUnitsText "best" }
								"HIGH"		{ set ourUnitsText "high" }
								"MEDIUM"	{ set ourUnitsText "medium" }
								"BASIC"		{ set ourUnitsText "basic" }
								default		{ set ourUnitsText "best" }
							}
							set ourhours 0
							set ourseconds 0
							set ourseconds [expr (($ourremainingspacemeg * 1024) / ($bitrate / (8 * 1024))) ]	
							set ourhours [expr (round((($ourseconds / 60) / 60) * 10)/10.0)]
							if {$ourhours < 1} { set ourhours 0 }
							set progremaininghours $ourhours
							if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-remaining hours >>$progremaininghours<<"}
						}
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-remaining time calc end"}

						## end of remaining time calculation      
						
						## SEASON PASS INFO

						set itemisseasonpass false
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-season pass match"}

						if {$::version >= 3} {
							if {$seltype == 2 || $seltype == 9 } {
								set itemisseasonpass true
							} else {
								set itemisseasonpass false
							}
							if {$seltype == 3 } {
								set itemiswishlist true
							} else {
								set itemiswishlist false
							}
						} else {
							if {$seltype == 9 || $seltype == 10 } {
								set itemisseasonpass true
							} else {
								set itemisseasonpass false
							}
							if {$seltype == 13 } {
								set itemiswishlist true
							} else {
								set itemiswishlist false
							}
						}

						## END OF SEASON PASS
						
						## PROGRAM TIMES & EXTRA INFO INC ENDPAD / SUGGESTION INFO

						## configure program status / details info display
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-configure details start"}
						set size [expr round($size)]
						set minutes [expr round($minutes)]	
						set icons ""
						set progstatustext ""
						if { $::progstatusdurationreq || $::progstatuspacereq || $::progstatuspercentageusedreq || $::progstatustimeremainingreq } {
							if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-prog status text required"}
							if {$::progstatusdurationreq} {
								append progstatustext "${minutes} Min"
							}
							if {$::progstatuspacereq} {
								if {$progstatustext != ""} {
									append progstatustext " | "
								}
								append progstatustext "${size} MB"
							}
							if {$::progstatuspercentageusedreq} {
								if {$progstatustext != ""} {
									append progstatustext " | "
								}								
								if {$percentusedafterprog > $::highthreshold } {
									append progstatustext "<b>${percentusedafterprog} %</b>"
									set ::alertstatus true
									append ::alertreasons "After Rec Low Space - "
								} else {
									append progstatustext "${percentusedafterprog} %"
								}
							}
							if {$::progstatustimeremainingreq} {
								if {$progstatustext != ""} {
									append progstatustext " | "
								}	
								append progstatustext "${progremaininghours} Hrs"
							}
							if {$progstatustext != ""} {
								set progstatustext "&nbsp;\[${progstatustext}\]"
							}
						}
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-status text >>$progstatustext<<"}
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-configure details end"}
						## end of configure program status / details info display
						
						## from start time to icons

						if {$seltype == 6} {
							writehtml "$starttime - $endtime $callsign"
							if {$::suggestiongraphicreq} {
								if {$::graphicson} {
									append icons "&nbsp;<img src=\"[imageref $::suggestiongraphic]\" border=\"0\" alt=\"Sug\" title=\"Suggestion\"></td><td valign=middle class=invisible>\n"
								} else {
									append icons "&nbsp;SUG"
								}
							} else {
								writehtml "&nbsp;(Suggestion)"
							}
							writehtml "$progstatustext"

							if {$otherprogremovaladdbackicon != ""} {
								if {$::graphicson} {
									append icons "$otherprogremovaladdbackicon\n"
								} else {
									append icons "&nbsp;<b>CLR</b>"
								}
							} 

							if {$addbackicon != ""} {
								if {$::graphicson} {
									append icons "$addbackicon\n"
								} else {
									append icons "&nbsp;<b>+</b>"
								}
							} 

							if {$percentusedafterprog > $::highthreshold && $percentusedafterprog < 100} {
								if {$::proglevelhighspaceindreq} {
									set ::alertstatus true
									append ::alertreasons "After Rec Low Space - "
									if {$::graphicson} {
										append icons "&nbsp;<img src=\"[imageref $::exclaimgraphic]\" border=\"0\" title=\"Warning! Once this p${program_word} has recorded you will be at ${percentusedafterprog}% of your available drive space!\" alt=\"!\"></td><td valign=middle class=invisible>\n"
									} else {
										append icons "&nbsp;<b>!</b>"
									}
								}
							} elseif {$percentusedafterprog > $::highthreshold && $percentusedafterprog >= 100} {
								if {$::proglevelhighspaceindreq} {
									set ::alertstatus true
									append ::alertreasons "After Rec No Space - "
									if {$::graphicson} {
										append icons "&nbsp;<img src=\"[imageref $::flashingexclaimgraphic]\" border=\"0\" title=\"Warning! Once this p${program_word} has recorded you will have no space remaining! You must o${organize_word} your p${program_word}s immediately!\" alt=\"--!--\"></td><td valign=middle class=invisible>\n"
									} else {
										append icons "&nbsp;<b>--!--</b>"
									}
								}

							}
							if { $::endpadinstalled && $::endpadstatus && $::endpadtodoliston} {
								if { [ strim [ lindex $endpadrecstatus $currentcount ] ] == "NoRecord" } {
									set ::alertstatus true
									append ::alertreasons "Suggestion No Record - "
									if {$::graphicson} {
										append icons "&nbsp;<img src=\"[imageref $::endpadrecordingunlikelygraphic]\" border=\"0\" alt=\"No Record\" title=\"Soft&nbsp;padding&nbsp;makes&nbsp;this&nbsp;recording&nbsp;unlikely. [lindex $norecordmessage $currentcount]\"></td><td valign=middle class=invisible>\n"
									} else {
										append icons "&nbsp;<b>NR</b>"
									}
								}
							}
						} else {
							writehtml "$starttime - $endtime $callsign"
							writehtml "$progstatustext"

							if {$otherprogremovaladdbackicon != ""} {
								if {$::graphicson} {
									append icons "$otherprogremovaladdbackicon\n"
								} else {
									append icons "&nbsp;<b>CLR</b>"
								}
							} 

							if {$addbackicon != ""} {
								if {$::graphicson} {
									append icons "$addbackicon\n"
								} else {
									append icons "&nbsp;<b>+</b>"
								}
							} 

							if {$percentusedafterprog > $::highthreshold && $percentusedafterprog < 100} {
								if {$::proglevelhighspaceindreq} {
									set ::alertstatus true
									append ::alertreasons "After Rec Low Space - "
									if {$::graphicson} {
										append icons "&nbsp;<img src=\"[imageref $::exclaimgraphic]\" border=\"0\" title=\"Warning! Once this p${program_word} has recorded you will be at ${percentusedafterprog}% of your available drive space!\" alt=\"!\"></td><td valign=middle class=invisible>\n"
									} else {
										append icons "&nbsp;<b>!</b>"
									}
								}
							} elseif {$percentusedafterprog > $::highthreshold && $percentusedafterprog >= 100} {
								if {$::proglevelhighspaceindreq} {
									set ::alertstatus true
									append ::alertreasons "After Rec No Space - "
									if {$::graphicson} {
										append icons "&nbsp;<img src=\"[imageref $::flashingexclaimgraphic]\" border=\"0\" title=\"Warning! Once this p${program_word} has recorded you will have no space remaining! You must o${organize_word} your p${program_word}s immediately!\" alt=\"--!--\"></td><td valign=middle class=invisible>\n"
									} else {
										append icons "&nbsp;<b>--!--</b>"
									}
								}

							}
						}
						if { $::endpadinstalled && $::endpadstatus && $::endpadtodoliston} {
							if {$::paddinggraphicsreq} {
								if {$::graphicson} {
									if {[lindex $frontpadding $currentcount] > 0} {
										append icons "&nbsp;<img src=\"[imageref $::startpaddinggraphic]\" border=\"0\" title=\"[lindex $frontpadding $currentcount] mins start padding will be added to p${program_word}.\" alt=\"SP[lindex $frontpadding $currentcount]\"></td><td valign=middle class=invisible>\n"	
									}
									if {[lindex $backpadding $currentcount] > 0} {
										append icons "&nbsp;<img src=\"[imageref $::endpaddinggraphic]\" border=\"0\" title=\"[lindex $backpadding $currentcount] mins end padding will be added to p${program_word}.\" alt=\"EP[lindex $backpadding $currentcount]\"></td><td valign=middle class=invisible>\n"
									}
								} else {
									if {[lindex $frontpadding $currentcount] > 0} {
											append icons "&nbsp;SP[lindex $frontpadding $currentcount]"
									}
									if {[lindex $backpadding $currentcount] > 0} {
											append icons "&nbsp;EP[lindex $backpadding $currentcount]"
									}
								}
							}
						}

						if { $::shownewepisodeprogramicon} {
							if {$newepisode} {
								if {$::graphicson} {
									append icons "&nbsp;<img src=\"[imageref $::newepisodegraphic]\" border=\"0\" title=\"New!\" alt=\"New\"></td><td valign=middle class=invisible>\n"		
								} else {
									append icons "&nbsp;NEW"
								}
							}
						}

						if { $::showseasonpasswishlisticon} {
							if {$itemisseasonpass || $itemiswishlist} {
								if {$::graphicson} {
									append icons "&nbsp;<img src=\"[imageref $::seasonpassgraphic]\" border=\"0\" "
									if {$itemisseasonpass} {
										append icons "title=\"Season Pass\" alt=\"Pass\">"
									} else {
										append icons "title=\"Wish List\" alt=\"Wish\">"
									}
									append icons "</td><td valign=middle class=invisible>\n"
								} else {
									if {$itemisseasonpass} {
										append icons "&nbsp;PASS"
									} else {
										append icons "&nbsp;WISH"
									}						
								}
							}
						}

						## end of from start time to icons
						
						## END OF PROGRAM TIME & EXTRA INFO
						
						## TRACKER CODE
						if { $::trackerblockreq  || $::globalblockreq } {
							if {$blockthis=="Yes"} {
								if {$::graphicson} {
									append icons "&nbsp;<img src=\"[imageref $::trackerblockfilename]\" border=\"0\" title=\"This p${program_word} has been "
									if {$::todomultidelete} {
										if {$globalblock == ""} {
											append icons "previously recorded and is on your block list. The corresponding delete checkbox has been pre-selected for your convenience"
										} else {
											append icons "marked on your global block list. The corresponding delete checkbox has been pre-selected for your convenience"
										}
									} else {
										if {$globalblock == ""} {
											append icons "previously recorded and is on your block list"
										} else {
											append icons "marked on your global block list"
										}		
									}
									append icons ".\" alt=\"X\"></td><td valign=middle class=invisible>\n"
								} else {
									append icons "&nbsp;BLK"
								}
							}
						}
						## END TRACKER CODE
						
						## Global Block Extra Functionality function
						
						if { $::dmailLinksOn && $::globalblockfunction} {
							append icons "&nbsp;<a href=\"$::dmailTivoURL/blocklist_addremove/$title\" title=\"Click here to "
							if { $blockthis=="Yes" && $globalblock == "Yes" } {
								if {$::graphicson} {
									append icons "remove this title from your global block list.\" target=\"_blank\"><img src=\"[imageref $::unblockmegraphic]\" border=\"0\" title=\"Click here to remove this title from your global block list.\" alt=\"U\">"
								} else {
									append icons "remove this title from your global block list.\" target=\"_blank\">U"										
								}
							} else {
								if {$::graphicson} {
									append icons "add this title to your global block list.\" target=\"_blank\"><img src=\"[imageref $::blockmegraphic]\" border=\"0\" title=\"Click here to add this title to your global block list.\" alt=\"B\">"										
								} else {
									append icons "add this title to your global block list.\" target=\"_blank\">B"										
								}	
							}
							append icons "</a></td><td valign=middle class=invisible>\n"
						}
						
						## End of Global Block Extra Functionality function
						
						## Display Icons or substitutes

						if {$::graphicson} {
							if {$icons != ""} {
								writehtml "</td><td valign=middle class=invisible>${icons}</td></tr></table>\n"
							} else {
								writehtml "</td></tr></table>"
							}
						} else {
							if {$icons != ""} {
								writehtml "</td><td valign=middle class=ProgramAlert>${icons}&nbsp;</td></tr></table>\n"
							} else {
								writehtml "</td></tr></table>"
							}
						}

						## end of Display Icons or substitutes
						
						## EPISODE TITLE & DESCRIPTION

						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-within to-do loop - check point #12"}
						if {$eptitle !=""} {
							if {$descr !=""} {
								writehtml "$eptitle - $descr"
							} else {
								writehtml "$eptitle"
							}
						} else {
							if {$descr !=""} {
								writehtml "$descr"
							} else {
								writehtml "No description."
							}
						}

						## END OF EPISODE TITLE & DESCRIPTION
						
						## CANCEL & VIEW LINKS
						if {$::dmailLinksOn} {
							writehtml "</td><td class=links${rowclassid}>"
							writehtml "<a href=\"$::dmailTivoURL/confirmdelete/2/$fsid\" title=\"Click here to cancel recording.\" target=\"_blank\">cancel recording</a><br>"
							writehtml "<a href=\"$::dmailTivoURL/showing/$showingfsid\" title=\"Click here to view details.\" target=\"_blank\">view details</a>"
						}
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-within to-do loop - check point #13"}
						writehtml "</td>"

						## END OF CANCEL & VIEW LINKS
						
						## THUMB GRAPHICS
						if {$::graphicson} {
							if {$::viewthumbs} {
								if {$imagef != ""} {
									writehtml "<td class=thumbs${rowclassid}>"
									if {$::tivowebplususer} {
										writehtml "<img src=\"[imageref $imagef]\" title=\"Thumbs are $xthumbtype.\" alt=\"${thumbcount}${thumbtype}\">"
									} else {
										if {$::dmailLinksOn && $::series1} {
											writehtml "<a href=\"$::dmailTivoURL/thumbs/$seriesfsid\" target=\"_blank\" ><img src=\"[imageref $imagef]\" border=\"0\" title=\"Thumbs are $xthumbtype. Click&nbsp;here&nbsp;to&nbsp;update&nbsp;thumbs.\" alt=\"${thumbcount}${thumbtype}\"></a>"	
										} else {
											writehtml "<img src=\"[imageref $imagef]\" title=\"Thumbs are $xthumbtype.\" alt=\"${thumbcount}${thumbtype}\">"
										}
									}
									writehtml "</td>"
								} else {
									writehtml "<td class=thumbs${rowclassid}>&nbsp;"			
									writehtml "</td>"
								}
							}
						} else {
							if {$::viewthumbs} {
								if {$imagef != ""} {
									if {$thumbcount > 0} {
										set appendthumbtext "+"
									} else {
										set appendthumbtext ""
									}
									writehtml "<td class=thumbs${rowclassid}>"
									if {$::tivowebplususer} {
										writehtml "${appendthumbtext}${thumbcount}${thumbtype}"	
									} else {
										if {$::dmailLinksOn && $::series1} {
											writehtml "<a href=\"$::dmailTivoURL/thumbs/$seriesfsid\" target=\"_blank\" title=\"Thumbs are $xthumbtype. Click&nbsp;here&nbsp;to&nbsp;update&nbsp;thumbs.\">${appendthumbtext}${thumbcount}${thumbtype}</a>"	
										} else {
											writehtml "${appendthumbtext}${thumbcount}${thumbtype}"				
										}
									}
									writehtml "</td>"
								} else {
									writehtml "<td class=thumbs${rowclassid}>&nbsp;"			
									writehtml "</td>"
								}
							}			
						}
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-within to-do loop-check point #14"}

						## END OF THUMB GRAPHICS
						
						## MULTI THUMB UPDATE
						if {$::tivowebplususer} {
							## null
						} else {
							if {$::series1} {
								if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-multi thumb update item"}
								if {$::todomultithumbupdate} {
									if {$::dmailLinksOn} {
										writehtml "<td class=thumbupdate${rowclassid}>"
										set thumbitemmatch 0
										foreach tempitem $progressivethumbs {
											if {"$tempitem"=="$seriesfsid"} {
												set thumbitemmatch 1
											}
										}
										if {$thumbitemmatch==0} {
											set seriesfsidname "seriesfsid_"
											append seriesfsidname $ouritemid
											append seriesfsidname "_"
											append seriesfsidname $seriesfsid
											append seriesfsidname "_"
											append seriesfsidname $fsid
											if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-multi thumb update - checkpoint A"}
											writehtml "<select name=$seriesfsidname size=1 style=\"font-size: 8pt; font-family: Arial, sans-serif;\">"
											if {$thumbtype == "E" && $thumbcount == 3} {
												writehtml "<option value=\"N_3\" selected=TRUE>+3</option>"
											} else {
												writehtml "<option value=\"Y_3\">+3</option>"
											}
											if {$thumbtype == "E" && $thumbcount == 2} {
												writehtml "<option value=\"N_2\" selected=TRUE>+2</option>"
											} else {
												writehtml "<option value=\"Y_2\">+2</option>"
											}
											if {$thumbtype == "E" && $thumbcount == 1} {
												writehtml "<option value=\"N_1\" selected=TRUE>+1</option>"
											} else {
												writehtml "<option value=\"Y_1\">+1</option>"
											}
											if {($thumbtype == "E" && $thumbcount == 0) || ($thumbtype == "X")} {
												writehtml "<option value=\"N_0\" selected=TRUE>0</option>"
											} else {
												writehtml "<option value=\"Y_0\">0</option>"
											}
											if {$thumbtype == "E" && $thumbcount == -1} {
												writehtml "<option value=\"N_-1\" selected=TRUE>-1</option>"
											} else {
												writehtml "<option value=\"Y_-1\">-1</option>"
											}
											if {$thumbtype == "E" && $thumbcount == -2} {
												writehtml "<option value=\"N_-2\" selected=TRUE>-2</option>"
											} else {
												writehtml "<option value=\"Y_-2\">-2</option>"
											}
											if {$thumbtype == "E" && $thumbcount == -3} {
												writehtml "<option value=\"N_-3\" selected=TRUE>-3</option>"
											} else {
												writehtml "<option value=\"Y_-3\">-3</option>"
											}
											if {$thumbtype == "I" || $thumbtype == "P"} {
												writehtml "<option value=\"N_-999\"selected=TRUE>-</option>"
											} else {
												writehtml "<option value=\"Y_-999\">-</option>"
											}
											writehtml "</select>"
											if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-multi thumb update - checkpoint B"}
											lappend progressivethumbs "$seriesfsid"
										} else {
											if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-multi thumb update - checkpoint c"}
											if {$::graphicson} {
												writehtml "<img src=\"[imageref $::multiupdatethumbsblankboxfilename]\" border=\"0\" title=\"P${program_word} is in a duplicate series so thumb update option is not required. Update prior item in To Do list.\" alt=\"XXX\">"	
											}
										}
										writehtml "</td>"
									}
								}
							}
						}

						## END OF MULTI THUMB UPDATE
						
						## MULTI DELETE CHECKBOXES

						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-multi delete item"}
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-within to-do loop - check point #15"}
						if {$::todomultidelete} {
							if {$::dmailLinksOn} {
								if { ( $::trackerblockreq  || $::globalblockreq ) && $blockthis=="Yes"} {
									writehtml "<td class=actionblocked>"
								} else {
									writehtml "<td class=action${rowclassid}>"
								}
								set temptext "fsid_"
								append temptext $ouritemid
								append temptext "_"
								append temptext $fsid
								if { ( $::trackerblockreq  || $::globalblockreq ) && $blockthis=="Yes"} {
									writehtml "<input type=\"checkbox\" name=\"$temptext\" checked=TRUE >"
								} else {
									writehtml "<input type=\"checkbox\" name=\"$temptext\" >"
								}
								writehtml "</td>"
								writehtml "</tr>"
							}
						}

						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-within to-do loop - check point #16"}
						set ouritemid [ expr $ouritemid + 1 ]

						### END OF MULTI DELETE CHECKBOXES
						
					}
				} else {
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-disallowed program type - user defined - ignored"}
				}
				set currentcount [ expr $currentcount + 1 ]
			} else {
				# don't increment count for ignored invisible items
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-disallowed program type - invisible - ignored"}
			}
		
		}
		
	}
	
	# clear down variables 	
	foreach var [info vars] {
		catch {
			if {$var != "itemsFound"} {
				if { [catch { 
					if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-unsetting variable >>$var<<"}
				} fid] } {
					# null
				} else {
					if { [catch { 
						unset $var  
					} fid] } {
						if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-error in unsetting variable >>$var<<"}
					} 
				}
			}
		}
	}
	
	return $itemsFound
}



#####################################################
## Generate expiry list

proc getnpexpire {hoursahead} {

	set expirytitle "Dummy"
	set expiryrectime 999
	set expiryexpsecs 999
	set expiryeptitle "Dummy"
	set expirydescr "Dummy"
	set expiryfsid 999
	set expiryshowingfsid 999
	set expirycount 0
	set expiryfound 0
	set expiryseltype 0
	set expirycallsign "Dummy"
	set text ""
	set colourtoggle 1
	
	if {$::debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-compiling expiration list"}
	set message {}
	after 2000
	ForeachMfsFileTrans fsid name type $::nowshowingdir "" 10 {
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-checkpoint expire 000"}
		set debugfinished false
		catch {
			set rec [db $::db openid $fsid]	
			set expdate [dbobj $rec get ExpirationDate]
			set expsecs [expr $expdate * 86400 + [dbobj $rec get ExpirationTime]]
			if {$expsecs < [expr $hoursahead * 3600 + [clock seconds]] && $expsecs > [clock seconds] } {
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-debug-------new program"}
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-checkpoint expire 001"}
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-within time period"}
				set showing [dbobj $rec get Showing]
				set showingfsid [dbobj $rec gettarget Showing]
				set startdate [dbobj $rec get StartDate]
				set starttime 0
				set starttime [dbobj $rec get StartTime]
				if { $starttime == "" } {
					set starttime [dbobj $showing get Time]
				}
				if {$starttime == ""} {
					set starttime 0
				}
				set rectime [expr $startdate * 86400 + $starttime]
				set station [dbobj $showing get Station]
				set stationfsid [dbobj $station fsid]
				set callsign [dbobj $station get CallSign]
				set program [dbobj $showing get Program]
				set title [strim [dbobj $program get Title]]
				set descr [strim [dbobj $program get Description]]
				set series [dbobj $program get Series]
				if {$::version >= 3} {
					set recbeh [dbobj $rec get RecordingBehavior]
					set seltype [dbobj $recbeh get PresentationBehavior]
				} else {
					set seltype [dbobj $rec get SelectionType]
				}
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-checkpoint expire 002"}

				## IGNORE SELECTION / PRESENTATION ITEM 
				set ignorethisitem "N"
				foreach ignoreitem $::ignorelist {
					if { $ignoreitem ==  $seltype } {
						set ignorethisitem "Y"
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ignore item at user request"}
					}
				}
				##
				
				if {$ignorethisitem == "N"} {

					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-showing : >>$showing<<"}
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-showingfsid : >>$showingfsid<<"}
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-startdate : >>$startdate<<"}
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-starttime : >>$starttime<<"}
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-rectime : >>$rectime<<"}
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-station : >>$station<<"}
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-callsign : >>$callsign<<"}
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-title : >>$title<<"}
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-program:: >>$program<<"}
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-series : >>$series<<"}		
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-checkpoint expire 003"}
					if {$series != ""} {
						set episodic [defaultval 1 [dbobj $series get Episodic]]
					} else {
						set episodic 1
					}
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-checkpoint expire 004"}
					if { $episodic == 1 } {
						set eptitle [strim [dbobj $program get EpisodeTitle]]
						if { $eptitle == "" } {
							set eptitle "No Episode Title"
						}
					} else {
						set eptitle ""
					}
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-checkpoint expire 005"}
					lappend expirytitle $title
					lappend expiryrectime $rectime 
					lappend expiryexpsecs $expsecs
					lappend expiryeptitle $eptitle
					lappend expirydescr $descr
					lappend expiryfsid $fsid
					lappend expiryshowingfsid $showingfsid
					lappend expiryseltype $seltype
					lappend expirycallsign $callsign
					set expirycount [expr $expirycount + 1]
					set expiryfound 1
				}
			}
			set debugfinished true
		}
		if {$debugfinished} {
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-expiry item success"}
		} else {
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-expiry error occurred with item"}
		}
	}
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-debug--------------"}
	if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ready to go generate list."}
	## sort out the list generation aspect
	set runningcount 0
	## identify the current day as a base starting point
	set nowsecs [expr [clock seconds] +  $::tzoffset - $::listseperatoroffset]
	if {$::yankspeak} {
		set nowday [clock format [expr $nowsecs +  $::tzoffset - $::listseperatoroffset] -format {%A, %B %d}]
	} else {
		set nowday [clock format [expr $nowsecs  + $::tzoffset - $::listseperatoroffset] -format {%a, %d %b}]
	}
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-about to enter first loop."}	
	while { $runningcount < $expirycount } {
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-test day is >>$nowday<<"}
		set text {}
		set i 1
		set firstline "Y"
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-about to enter second loop"}
		while { $i <= $expirycount } {
			if {$::yankspeak} {
				set itemday [clock format [expr [lindex $expiryexpsecs $i]  + $::tzoffset - $::listseperatoroffset] -format {%A, %B %d}]
			} else {
				set itemday [clock format [expr [lindex $expiryexpsecs $i] + $::tzoffset - $::listseperatoroffset] -format {%a, %d %b}]
			}	
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-item day is >>$itemday<<"}
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-item details are >>[lindex $expirytitle $i]<< >>[lindex $expiryeptitle $i]<< >>[lindex $expiryfsid $i]<<"}
			if { $itemday == $nowday } {
				if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-day match identified!"}
				if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-matched item day is >>$itemday<<"}
				if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-matched item details are >>[lindex $expirytitle $i]<< >>[lindex $expiryeptitle $i]<< >>[lindex $expiryfsid $i]<<"}
				## sort out seperator line
				if {$firstline == "Y"} {
					if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-creating seperator line"}
					if {$::listseperator} {
						writehtml "<tr><td class=seperator>$nowday</td>"
						if {$::dmailLinksOn} {
							writehtml "<td class=links>&nbsp;</td>"				
						}
						writehtml "</tr>"
					}				
					set firstline "N"
				}
				## sort out the rest	
				if {$::multicolourbar} {
					set rowclassid "$colourtoggle"
					if {$colourtoggle == 1} {
						set colourtoggle 2
					} else {
						set colourtoggle 1
					}
				} else {
					set rowclassid ""
				}
				writehtml "<tr><td class=programme${rowclassid}>"
				writehtml "<table border=0 cellspacing=0 cellpadding=0><tr><td valign=middle class=invisible><strong>"
				writehtml "[lindex $expirytitle $i]" 
				writehtml "</strong>"
				if {$::yankspeak} {
					writehtml "Recorded [clock format [expr [lindex $expiryrectime $i] + $::tzoffset] -format {%A, %B %d %I:%M%p}] [lindex $expirycallsign $i]"
					writehtml " - Expires [clock format [expr [lindex $expiryexpsecs $i] + $::tzoffset] -format {%a %I:%M%p}]"				
				} else {
					writehtml "Recorded [clock format [expr [lindex $expiryrectime $i] + $::tzoffset] -format {%a, %d %b %H:%M}] [lindex $expirycallsign $i]"
					writehtml " - Expires [clock format [expr [lindex $expiryexpsecs $i] + $::tzoffset] -format {%a %H:%M}]"
				}
				if {[lindex $expiryseltype $i] == 6} {
					if {$::suggestiongraphicreq} {
						if {$::graphicson} {
							writehtml "</td><td valign=middle class=invisible>&nbsp;<img src=\"[imageref $::suggestiongraphic]\" border=\"0\" title=\"Suggestion\" alt=\"Sug\"></td></tr></table>"
						} else {
							writehtml "&nbsp;SUG</td></tr></table>"
						}
					} else {
						writehtml "&nbsp;(Suggestion)</td></tr></table>"
					}
				} else {
					writehtml "&nbsp;</td></tr></table>"
				}
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-checkpoint expire 006"}
				if {[lindex $expiryeptitle $i] !=""} {
					if {[lindex $expirydescr $i] !=""} {
						writehtml "[lindex $expiryeptitle $i] - [lindex $expirydescr $i]"
					} else {
						writehtml "[lindex $expiryeptitle $i]"
					}
				} else {
					if {[lindex $expirydescr $i] !=""} {
						writehtml "[lindex $expirydescr $i]"
					} else {
						writehtml "No description."
					}
				}
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-checkpoint expire 007"}
				if {$::dmailLinksOn} {
					writehtml "</td><td class=links${rowclassid}>"
					writehtml "<a href=\"$::dmailTivoURL/editprogram/[lindex $expiryfsid $i]\" title=\"Click here to edit recording.\" target=\"_blank\">edit recording</a><br>"
					writehtml "<a href=\"$::dmailTivoURL/showing/[lindex $expiryshowingfsid $i]\" title=\"Click here to view details.\" target=\"_blank\">view details </a>"
				}			
				writehtml "</td></tr>"				
				if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-item text added."}
				set runningcount [expr $runningcount + 1]
			}
			set i [expr $i + 1]
		}
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-second loop completed."}
		lappend message $text
		set nowsecs [expr $nowsecs + 86400]
		if {$::yankspeak} {
			set nowday [clock format [expr $nowsecs +  $::tzoffset - $::listseperatoroffset] -format {%A, %B %d}]
		} else {
			set nowday [clock format [expr $nowsecs  + $::tzoffset - $::listseperatoroffset] -format {%a, %d %b}]
		}
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-day augmented"}
	}
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-first loop completed"}


	# clear down variables 	
	foreach var [info vars] {
		catch {
			if {$var != "expiryfound"} {
				if { [catch { 
					if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-unsetting variable >>$var<<"}
				} fid] } {
					# null
				} else {
					if { [catch { 
						unset $var  
					} fid] } {
						if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-error in unsetting variable >>$var<<"}
					} 
				}
			}
		}
	}

	return $expiryfound
	catch { unset expiryfound }
}


##############################################################
## adapted from the phone.itcl module by Courtney Bailey

proc phone_status {} {

	set errormessages { "Blank" "Succeeded" "PendingRestart" \
		"InitializationFailure" "SettingUp" "InProgress" \
		"UnknownError" "Failure during Housekeeping" \
		"Failure during Preparation" "Failed. Line unavailable" \
		"Failed. No dial tone" "Failed. Couldn't dial" "Failed. Wrong number" \
		"Failed. Service is not answering" "Failed. Service unavailable" \
		"Failed. Service denied" "Failed. Call interrupted" \
		"Failed while expanding data" "Failed while preparing data" \
		"Failed while loading series" "Failed while indexing shows" "Failed to set clock" \
		"Failed getting account status" "Failure downloading messages" "Failed. Phone is busy" \
		"Failed while indexing days" "Failed getting account status" "In Progress" \
		"Housekeeping" "Preparing to call" "Dialing..." "Answering..." "Answered" \
		"Connecting..." "Getting account status" "Setting clock..." "Downloading messages" \
		"Processing..." "Downloading..." "Hanging up" "Expanding data" "Preparing data" \
		"Loading data" "Indexing series" "Indexing shows" "Indexing days" \
		"Failed. Modem is not responding" "Configuring modem" "Failed. No dial-in number chosen" \
		"Determining call status" "Failed. Busy calling" "Negotiating..." \
		"Configuring..." "Failed while negotiating" "Failed while configuring" \
! 		"Modem handshake failed" }
	if {$::version >= 3} {
		set config "/State/PhoneConfig"
		set serviceinfo $config
	} else {
		set config "/Setup"
		RetryTransaction {
			set configdir [db $::db open $config]
			set serviceinfo [dbobj $configdir get ServiceInfo]
		}
		catch { unset configdir }
	}
	RetryTransaction {
		set configdir [db $::db open $config]
		if {$::version >= 3} {
			set serviceinfo $configdir
		} else {
			set serviceinfo [dbobj $configdir get ServiceInfo]
		}
		set lastcallstatus [dbobj $configdir get LastCallStatus]
		if { $lastcallstatus == "Failed"} {
			set csi [dbobj $serviceinfo get CallStatusInfo]
			if {$csi != "Failed" } {
				regexp {[0-9]+} $csi lastcallstatus
				catch { set lastcallstatus [lindex $errormessages $lastcallstatus] }
			}
			return $lastcallstatus
		} else {
			set lastcallstatus "Ok"
			return $lastcallstatus
		}
		catch { unset configdir }
	}
	catch { unset lastcallstatus  }
	catch { unset serviceinfo  }
	catch { unset csi  }
	catch { unset config  }
	catch { unset errormessages }
}


###################################################################
## Define stylesheet 

proc outputStyleSheet {chan} {

	puts $chan "<style type='text/css'>"
	puts $chan "body"
	puts $chan "{"
	puts $chan "	margin: 10px 0px 0px 10px;"
	puts $chan "	font-size: 14px;"
	puts $chan "	font-family: Arial,helvetica,sans-serif;"
	puts $chan "	background-color: #ffffff;"
	puts $chan "	cursor: default;"
	puts $chan "}"
	puts $chan "a"
	puts $chan "{"
	puts $chan "	color: #305BB9;"
	puts $chan "}"
	puts $chan "table"
	puts $chan "{"
	puts $chan "	padding: 0px;"
	puts $chan "	margin: 0px;"
	puts $chan "}"
	puts $chan "table.indented"
	puts $chan "{"
	puts $chan "	margin-left: 32px;"
	puts $chan "}"
	puts $chan "table.section"
	puts $chan "{"
	puts $chan "	padding: 0px;"
#	puts $chan "	width: [expr $::programbarwidthpx + 57]px;"
	puts $chan "	margin: 0px 0px 0px 32px;"
	puts $chan "	background-color: #cccccc;"
	puts $chan "	border-collapse: collapse;"
	puts $chan "}"
	puts $chan "td.programme"
	puts $chan "{"
	puts $chan "	font-size: 14px;"
	puts $chan "	width: ${::programbarwidthpx}px;"
	puts $chan "	background-color: #cccccc;"
	puts $chan "	border-bottom: 2px solid #ffffff;"
	puts $chan "}"
	if {$::multicolourbar} {	
		puts $chan "td.programme1"
		puts $chan "{"
		puts $chan "	font-size: 14px;"
		puts $chan "	width: ${::programbarwidthpx}px;"
		puts $chan "	background-color: #AEB7D1;"
		puts $chan "	border-bottom: 2px solid #ffffff;"
		puts $chan "}"	
		puts $chan "td.links1"
		puts $chan "{"
		puts $chan "	font-size: 12px;"
		puts $chan "	text-align: center;"
		puts $chan "	width: 100px;"
		puts $chan "	background-color: #AEB7D1;"
		puts $chan "	border-left: 2px solid #ffffff;"
		puts $chan "	border-bottom: 2px solid #ffffff;"
		puts $chan "}"
		puts $chan "td.thumbs1"
		puts $chan "{"
		puts $chan "	font-size: 12px;"
		puts $chan "	text-align: center;"
		puts $chan "	width: 50px;"
		puts $chan "	background-color: #AEB7D1;"
		puts $chan "	border-left: 2px solid #ffffff;"
		puts $chan "	border-bottom: 2px solid #ffffff;"
		puts $chan "}"
		puts $chan "td.thumbupdate1"
		puts $chan "{"
		puts $chan "	font-size: 12px;"
		puts $chan "	text-align: center;"
		puts $chan "	width: 50px;"
		puts $chan "	background-color: #AEB7D1;"
		puts $chan "	border-left: 2px solid #ffffff;"
		puts $chan "	border-bottom: 2px solid #ffffff;"
		puts $chan "}"
		puts $chan "td.action1"
		puts $chan "{"
		puts $chan "	font-size: 12px;"
		puts $chan "	text-align: center;"
		puts $chan "	width: 36px;"
		puts $chan "	background-color: #AEB7D1;"
		puts $chan "	border-left: 2px solid #ffffff;"
		puts $chan "	border-bottom: 2px solid #ffffff;"
		puts $chan "}"
		puts $chan "td.programme2"
		puts $chan "{"
		puts $chan "	font-size: 14px;"
		puts $chan "	width: ${::programbarwidthpx}px;"
		puts $chan "	background-color: #CCDAFF;"
		puts $chan "	border-bottom: 2px solid #ffffff;"
		puts $chan "}"	
		puts $chan "td.links2"
		puts $chan "{"
		puts $chan "	font-size: 12px;"
		puts $chan "	text-align: center;"
		puts $chan "	width: 100px;"
		puts $chan "	background-color: #CCDAFF;"
		puts $chan "	border-left: 2px solid #ffffff;"
		puts $chan "	border-bottom: 2px solid #ffffff;"
		puts $chan "}"
		puts $chan "td.thumbs2"
		puts $chan "{"
		puts $chan "	font-size: 12px;"
		puts $chan "	text-align: center;"
		puts $chan "	width: 50px;"
		puts $chan "	background-color: #CCDAFF;"
		puts $chan "	border-left: 2px solid #ffffff;"
		puts $chan "	border-bottom: 2px solid #ffffff;"
		puts $chan "}"
		puts $chan "td.thumbupdate2"
		puts $chan "{"
		puts $chan "	font-size: 12px;"
		puts $chan "	text-align: center;"
		puts $chan "	width: 50px;"
		puts $chan "	background-color: #CCDAFF;"
		puts $chan "	border-left: 2px solid #ffffff;"
		puts $chan "	border-bottom: 2px solid #ffffff;"
		puts $chan "}"
		puts $chan "td.action2"
		puts $chan "{"
		puts $chan "	font-size: 12px;"
		puts $chan "	text-align: center;"
		puts $chan "	width: 36px;"
		puts $chan "	background-color: #CCDAFF;"
		puts $chan "	border-left: 2px solid #ffffff;"
		puts $chan "	border-bottom: 2px solid #ffffff;"
		puts $chan "}"	
	}
	puts $chan "td.invisible"
	puts $chan "{"
	puts $chan "	font-size: 14px;"
	puts $chan "	x-cell-content-align: center;"
	puts $chan "}"
	puts $chan "td.justfont"
	puts $chan "{"
	puts $chan "	font-size: 14px;"
	puts $chan "	x-cell-content-align: center;"
	puts $chan "}"
	puts $chan "td.seperator"
	puts $chan "{"
	puts $chan "	font-size: 15px;"
	puts $chan "	color: #305BB9;"
	puts $chan "	width: ${::programbarwidthpx}px;"
	puts $chan "	background-color: #cccccc;"
	puts $chan "	border-bottom: 2px solid #ffffff;"
	puts $chan "}"
	puts $chan "td.suggestion"
	puts $chan "{"
	puts $chan "	font-size: 14px;"
	puts $chan "	width: ${::programbarwidthpx}px;"
	puts $chan "	background-color: #F8E9E4;"
	puts $chan "	border-bottom: 2px solid #ffffff;"
	puts $chan "}"	
	puts $chan "td.unresolved"
	puts $chan "{"
	puts $chan "	font-size: 14px;"
	puts $chan "	width: ${::programbarwidthpx}px;"
	puts $chan "	background-color: #F8E9E4;"
	puts $chan "	border-bottom: 2px solid #ffffff;"
	puts $chan "}"	
	puts $chan "td.blockedprogramme"
	puts $chan "{"
	puts $chan "	font-size: 14px;"
	puts $chan "	width: ${::programbarwidthpx}px;"
	puts $chan "	background-color: #ffffcc;"
	puts $chan "	border-bottom: 2px solid #ffffff;"
	puts $chan "}"		
	puts $chan "td.header"
	puts $chan "{"
	puts $chan "	font-size: 14px;"
	puts $chan "	width: [expr $::programbarwidthpx + 100]px;"
	puts $chan "	background-color: #ffffff;"
	puts $chan "}"	
	puts $chan "td.links"
	puts $chan "{"
	puts $chan "	font-size: 12px;"
	puts $chan "	text-align: center;"
	puts $chan "	width: 100px;"
	puts $chan "	border-left: 2px solid #ffffff;"
	puts $chan "	border-bottom: 2px solid #ffffff;"
	puts $chan "}"
	puts $chan "td.thumbs"
	puts $chan "{"
	puts $chan "	font-size: 12px;"
	puts $chan "	text-align: center;"
	puts $chan "	width: 50px;"
	puts $chan "	border-left: 2px solid #ffffff;"
	puts $chan "	border-bottom: 2px solid #ffffff;"
	puts $chan "}"
	puts $chan "td.thumbupdate"
	puts $chan "{"
	puts $chan "	font-size: 12px;"
	puts $chan "	text-align: center;"
	puts $chan "	width: 50px;"
	puts $chan "	border-left: 2px solid #ffffff;"
	puts $chan "	border-bottom: 2px solid #ffffff;"
	puts $chan "}"
	puts $chan "td.action"
	puts $chan "{"
	puts $chan "	font-size: 12px;"
	puts $chan "	text-align: center;"
	puts $chan "	width: 36px;"
	puts $chan "	border-left: 2px solid #ffffff;"
	puts $chan "	border-bottom: 2px solid #ffffff;"
	puts $chan "}"
	puts $chan "td.actionblocked"
	puts $chan "{"
	puts $chan "	font-size: 12px;"
	puts $chan "	text-align: center;"
	puts $chan "	width: 36px;"
	puts $chan "	background-color: #ffffcc;"
	puts $chan "	border-left: 2px solid #ffffff;"
	puts $chan "	border-bottom: 2px solid #ffffff;"
	puts $chan "}"
	puts $chan " .PageHeading"
	puts $chan "{"
	puts $chan "	color: #305BB9;"
	puts $chan "	font-size: 18px;"
	puts $chan "	font-weight: bold;"
	puts $chan "}"
	puts $chan " .SectionHeading"
	puts $chan "{"
	puts $chan "	color: #305BB9;"
	puts $chan "	font-size: 16px;"
	puts $chan "	font-weight: bold;"
	puts $chan "}"
	puts $chan " .Warning"
	puts $chan "{"
	puts $chan "	color: #952B42;"
	puts $chan "	font-size: 14px;"
	puts $chan "	font-weight: bold;"
	puts $chan "}"
	puts $chan " .ProgramAlert"
	puts $chan "{"
	puts $chan "	color: #952B42;"
	puts $chan "	font-size: 14px;"
	puts $chan "	x-cell-content-align: center;"
	puts $chan "}"
	puts $chan " .Normal"
	puts $chan "{"
	puts $chan "	font-size: 14px;"
	puts $chan "}"
	puts $chan " .Message"
	puts $chan "{"
	puts $chan "	font-size: 14px;"
	puts $chan "	color: #952B42;"
	puts $chan "	background-color: #FFFFCC;"
	puts $chan "}"
	puts $chan "</style>"
	catch {unset chan}
}

##############################################################
# Output the specified section

proc outputSection {index} {

	global errorInfo

	set sectionHeading ""
	set sectionWithData ""
	set sectionWithoutData ""
	set sectionMessage ""
	set itemsFound 1
	
	if {$::yankspeak} {
		set program_word "rogram"
		set expiry_word "xpiry"
	} else {
		set program_word "rogramme"
		set expiry_word "xpiration"
	}

	if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-generating output section >>$index<<"}
								
	## TO DO LIST CODE
	
	if { $::dmailToDoList == $index } {
	
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-generating to-do list"}
		
		writehtml "<br><span class=SectionHeading>To Do</span><br>"
		writehtml "<table><tr><td class=header>"
		writehtml "The following p${program_word}s are scheduled to record in the next $::dmailHoursahead hours: "
		writehtml "</td></tr></table>"
		writehtml "<form method=POST action=\"$::dmailTivoURL/handle_multi_events/\" name=todoform target=\"_blank\">"
		writehtml "<table class=section>"

		if { [catch { set itemsFound [ gettodo $::dmailHoursahead ] } fid] } {
			set itemsFound -1
			if {$::debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ERROR IN GETTODO MODULE >>$fid<<"}
		}
	
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Items Found >>$itemsFound<<"}

		if { $itemsFound == 0 } {
			writehtml "<tr><td class=programme>None</td></tr>"
		}
		if { $itemsFound == -1 } {
			writehtml "</table><table><tr><td class=programme>Error When Generating To Do List - See Log - $fid</td></tr>"
			if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
			if {$::debuglvl>0} { puts "$errorInfo"}
			if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
		}

		writehtml "</table>"
		writehtml "</form>"
		
	## NOW SHOWING CODE
	
	} elseif { $::dmailShowing == $index } {

		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-generating now showing list"}

		writehtml "<br><span class=SectionHeading>Now Showing</span><br>"
	
		writehtml "<table><tr><td class=header>"
		if {$::nowshowingdaylimit != 0} {
			writehtml "The following recordings are currently available on this TiVo. This list only includes those p${program_word}s recorded in the last $::nowshowingdaylimit days:"
		} else {
			writehtml "The following recordings are currently available on this TiVo: "
		}
		
		
		
		writehtml "</td></tr></table>"
		writehtml "<form method=POST action=\"$::dmailTivoURL/handle_multi_events/\" name=nowshowingform target=\"_blank\">"
		writehtml "<table class=section>"

		if { [catch { set itemsFound [ getnowshowing ] } fid] } {
			set itemsFound -1
			if {$::debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ERROR IN NOW SHOWING MODULE >>$fid<<"}
		}  

		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Items Found >>$itemsFound<<"}

		if { $itemsFound == 0 } {
			writehtml "<tr><td class=programme>None</td></tr>"
		}
		
		if { $itemsFound == -1 } {
			writehtml "</table><table><tr><td class=programme>Error When Generating Now Showing List - See Log - $fid</td></tr>"
			if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
			if {$::debuglvl>0} { puts "$errorInfo"}
			if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
		}

		writehtml "</table>"
		writehtml "</form>"
		
	## CONFLICTS LIST CODE
	
	} elseif { $::dmailConflicts == $index } {
	
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-generating conflicts list"}
        
		writehtml "<br><span class=SectionHeading>Conflicts</span><br>"
		writehtml "<table><tr><td class=header>"
		writehtml "The following unresolvable conflicts occur in the next $::dmailHoursahead hours. "
		writehtml "TiVo has determined that these p${program_word}s that you have selected to be recorded via season-pass or wishlist <b>will not be recorded</b>:"
		writehtml "</td></tr></table>"
		writehtml "<br><table class=section>"
		
		if { [catch { set itemsFound [ getconflicts $::dmailHoursahead ] } fid] } {
			set itemsFound -1
			if {$::debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ERROR IN CONFLICTS MODULE >>$fid<<"}
		}  
		
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Items Found >>$itemsFound<<"}
			
		if { $itemsFound == 0 } {
			writehtml "<tr><td class=programme>None</td></tr>"
		}
		if { $itemsFound == -1 } {
			writehtml "</table><table><tr><td class=programme>Error When Generating Conflicts List - See Log - $fid</td></tr>"
			if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
			if {$::debuglvl>0} { puts "$errorInfo"}
			if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
		}

		if {$::dmailLinksOn} {
			if { $itemsFound > 0 } {
				if { $::confresInstalled } {
					if { $::confresUseForm } {
						writehtml "<tr><td class=justfont>"
						writehtml "<b>Conflict Resolver</b>"
						writehtml "<br>"
						writehtml "<TABLE border=0 cellspacing=0 cellpadding=0 >"
						writehtml "<FORM METHOD=\"GET\" ACTION=\"$::dmailTivoURL/findconfs\" target=\"_blank\">"
						writehtml "<TR><TD class=justfont>Alternate TiVo (name or IP Address): </TD>"
						writehtml "<TD class=justfont><INPUT TYPE=TEXT NAME=\"tivoname\" SIZE=35 VALUE=\"$::confresDefaultOtherTiVo\"></TD></TR>"
						writehtml "<TR><TD class=justfont>Number of days ahead to look: </TD>"
						writehtml "<TD class=justfont><INPUT TYPE=TEXT NAME=\"daysahead\" SIZE=35 VALUE=\"$::confresDefaultDaysAhead\"></TD></TR>"
						writehtml "<TR><TD class=justfont>&nbsp;</TD><TD><INPUT TYPE=\"submit\" NAME=\"Save\" VALUE=\"Next\"></TD></TR>"
						writehtml "</FORM>"
						writehtml "</TABLE>"
					} else {
						writehtml "<tr><td class=justfont>"
						writehtml "<a align=center href=\"$::dmailTivoURL/findconfs?tivoname=$::confresDefaultOtherTiVo&daysahead=$::confresDefaultDaysAhead&Save=Next\" target=\"_blank\" title=\"Click here to resolve conflicts.\">"
						writehtml "Click here to resolve these conflicts</a> with the designated alternate TiVo (${::confresDefaultOtherTiVo})."
					}
					writehtml "</td></tr>"
				}
			}
		}
		writehtml "</table>"
		
	## EXPIRED LIST CODE

	} elseif { $::dmailExpired == $index } {

		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-generating expiry list"}

		writehtml "<br><span class=SectionHeading>E${expiry_word}</span><br>"
		writehtml "<table><tr><td class=header>"
		writehtml "The following recordings are due to expire in the next $::dmailHoursahead hours: "
		writehtml "</td></tr></table>"
		writehtml "<br><table class=section>"

		if { [catch { set itemsFound [ getnpexpire $::dmailHoursahead ] } fid] } {
			set itemsFound -1
			if {$::debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ERROR IN EXPIRY MODULE >>$fid<<"}
		}  

		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Items Found >>$itemsFound<<"}

		if { $itemsFound == 0 } {
			writehtml "<tr><td class=programme>None</td></tr>"
		}
		
		if { $itemsFound == -1 } {
			writehtml "</table><table><tr><td class=programme>Error When Generating Expired List - See Log - $fid</td></tr>"
			if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
			if {$::debuglvl>0} { puts "$errorInfo"}
			if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
		}

		writehtml "</table>"
		
	## STATUS LIST CODE
		
	} elseif { $::dmailTivoStatus == $index } {

		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-generating status list"}
		writehtml "<br><span class=SectionHeading>Status</span><br>"
		writehtml "<table><tr><td class=header>"
		if {$::yankspeak} {
			writehtml "Here is the status of your TiVo as of <i>[clock format [expr [clock seconds] + $::tzoffset] -format {%A, %B %d %I:%M:%S%p}]</i>: "
		} else {
			writehtml "Here is the status of your TiVo as of <i>[clock format [clock seconds] -format {%a, %d %b %H:%M} -gmt true]</i>: "
		}
		writehtml "</td></tr></table>"
		writehtml "<br><table class=section>"

		if { [catch { gettempuptime } fid] } {
			set itemsFound -1
			if {$::debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ERROR IN STATUS MODULE >>$fid<<"}
		} else {
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GetTempUpTime module completed ok"}
		}
		
		if { $itemsFound == -1 } {
			writehtml "</table><table><tr><td class=programme>Error When Generating Status List - See Log - $fid</td></tr>"
			if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
			if {$::debuglvl>0} { puts "$errorInfo"}
			if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
		}
		writehtml "</table>"
		
	## RECORD HISTORY LIST CODE
	
	} elseif { $::dmailRecHistory == $index } {
	
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-generating record history list"}
		writehtml "<br><span class=SectionHeading>Rejected Recordings</span><br>"
		writehtml "<table><tr><td class=header>"
		if {$::rejectedrecreq == 0} {
			writehtml "The following p${program_word}s either were not recorded in the last $::dmailHoursahead hours or will not be recorded within the next $::dmailHoursahead hours : "
		} elseif {$::rejectedrecreq == -1} {
			writehtml "The following p${program_word}s were not recorded in the last $::dmailHoursahead hours : "
		} elseif {$::rejectedrecreq == 1} {
			writehtml "The following p${program_word}s will not be recorded within the next $::dmailHoursahead hours : "
		} else {
			writehtml "No rejected recordings list information available."
		}
		writehtml "</td></tr></table>"
		writehtml "<br><table class=section>"

		if { [catch { set itemsFound [ recordhistory ] } fid] } {
			set itemsFound -1
			if {$::debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ERROR IN RECORD HISTORY MODULE >>$fid<<"}
		} 
		
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Items Found >>$itemsFound<<"}

		if { $itemsFound == 0 } {
			writehtml "<tr><td class=programme>None</td></tr>"
		}
		if { $itemsFound == -1 } {
			writehtml "</table><table><tr><td class=programme>Error When Generating Rejected Recording List - See Log - $fid</td></tr>"
			if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
			if {$::debuglvl>0} { puts "$errorInfo"}
			if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
		}
		writehtml "</table>"
	}
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-handle section module completed ok"}
	
	# clear down variables 	
	foreach var [info vars] {
		catch {
			if {$var != ""} {
				if { [catch { 
					if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-unsetting variable >>$var<<"}
				} fid] } {
					# null
				} else {
					if { [catch { 
						unset $var  
					} fid] } {
						if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-error in unsetting variable >>$var<<"}
					} 
				}
			}
		}
	}
}
##################################################################################################################
## Get the temperature, uptime, and apps running

proc gettempuptime {} {
		
	if {$::debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-reading the temperature, calculating uptime, checking what's running "}
	if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-about to run thermal check"}
	set cur_temp [exec cat /proc/therm]
	if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-thermal check run"}
  	set cur_tempF [expr 1.8*[string trim $cur_temp 'C']+32]F
  	if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-about to run uptime check"}
  	set uptime [lindex [exec cat /proc/uptime] 0]
  	if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-uptime check run"}
  	set uptime [expr int($uptime)]
  	set uptimestr [format "%d days, %d hours, %d minutes and %d seconds" [expr $uptime / 86400] [expr ($uptime % 86400) / 3600] [expr ($uptime % 3600) / 60] [expr $uptime % 60]]
  	set digit_tempC [expr [string trim $cur_temp 'C']]
	if {$digit_tempC < $::verylowtempcentigrade} {
		set temp_comment "Running cool -- the case must be open"
	}   elseif {$digit_tempC < $::lowtempcentigrade}  {
		set temp_comment "Running in the lower range of normal"
	}   elseif {$digit_tempC < $::midtempcentigrade}  {
		set temp_comment "Running in the middle range of normal"
	}   elseif {$digit_tempC < $::hightempcentigrade}  {
		set temp_comment "Running in the upper range of normal"
	}   elseif {$digit_tempC < $::toohightempcentigrade}  {
		set temp_comment "<b>Starting to run hot!  Watch it!</b>"
	}   elseif {$digit_tempC < $::emergencytempcentigrade}  {
		set temp_comment "<b>Your TiVo is running hot!  It should be shut down.</b>"
	}   else {
		set temp_comment "<b>TiVo is way too hot!  Shut it down right NOW!<b>"
	}
	writehtml "<tr><td class=programme>TiVo temperature is $cur_temp / $cur_tempF ($temp_comment).</td></tr>"
	writehtml "<tr><td class=programme>TiVo has been up for $uptimestr.</td></tr>"
	
	## get and display daily call information
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-check call information"}
        
        set complexcallstuff false
        
 	if {$::version >= 4} {
 		RetryTransaction {
 			set config [db $::db open "/State/PhoneConfig"]
 			set LSCday [dbobj $config get LastSuccessCallDay]
 			set NSCday [dbobj $config get NextCallAttemptDays]
 			set LSC [dbobj $config get LastSuccessCallSecInDay]
 			set NSC [dbobj $config get NextCallAttemptSecInDay]
 			set LSC [expr $LSC + ($LSCday * 86400)]
 			set NSC [expr $NSC + ($NSCday * 86400)]
 			set complexcallstuff true
 		}
 		catch { unset LSCday }
 		catch { unset NSCday }
 	} elseif {$::version >= 3} {
 		RetryTransaction {
 			set config [db $::db open "/State/PhoneConfig"]
 			set LSC [dbobj $config get LastSuccessCallSecInDay]
 			set NSC [dbobj $config get NextCallAttemptSecInDay]
 		}
 	} else {
 		RetryTransaction {
 			set config [db $::db open "/Setup"]
 			set LSC [dbobj $config get LastSuccessCall]
 			set NSC [dbobj $config get NextCallAttempt]
 		}
  	}
  	
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-check call information - checkpoint a"}
	
	proc GetGuideData { } {
		set count 0
		set lastday 0
		after 2000
		ForeachMfsFile fsid name type /Schedule "" {
			set date [lindex [split $name ":"] 1]
			if { $date > $lastday } {
				set lastday $date
			}
			incr count
			if { $count >= 100 } {
				return $lastday
			}
		}
		return $lastday
		catch {unset count}
		catch {unset lastday}
		catch {unset date}
		catch {unset name}
	} 
	
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-check call information - checkpoint b"}
	
	if { [catch { set GDT [GetGuideData] } fidx] } {
		if {$::debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-check call information - ERROR - can't get GuideDataThrough info: >>$fidx<<."}
		set GDT "UNKNOWN"
	}
	
	if {$complexcallstuff} {
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Printing Complex Call Information" }
		set LastSuccessfulCall [clock format [expr (($LSC * 86400) + $LSCS) + $::tzoffset] -format "%A, %B %d, %Y at %I:%M%p"]
		set NextScheduledCall [clock format [expr (($NSC * 86400) + $NSCS) + $::tzoffset] -format "%A, %B %d, %Y at %I:%M%p"]
		if {$GDT == "UNKNOWN"} {
			set GuideDataThrough "Unknown"
		} else {
			set GuideDataThrough [clock format [expr ($GDT * 86400) + $::tzoffset] -format "%A, %B %d %Y"]
		}
	} else {
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Printing Simple Call Information" }
		set LastSuccessfulCall [clock format [expr $LSC + $::tzoffset] -format "%a, %d %b at %H:%M"]
		set NextScheduledCall [clock format [expr $NSC + $::tzoffset] -format "%a, %d %b at %H:%M"]
		if {$GDT == "UNKNOWN"} {
			set GuideDataThrough "Unknown"
		} else {
			set GuideDataThrough [clock format [expr ($GDT * 86400)+ $::tzoffset] -format "%a, %d %b %Y"]
		}
	}

	writehtml "<tr><td class=programme>The following daily call information is available:"
	writehtml "<ul style='margin-top:0.1cm; margin-bottom:0cm' type=disc>"
	writehtml "<li>Last successful call: $LastSuccessfulCall</li>"
	writehtml "<li>Next scheduled call: $NextScheduledCall</li>"
	writehtml "<li>Guide data exists through: $GuideDataThrough</li></ul></td></tr>"

	set cronactive 0
	
	##
	
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-hack application test start"}
	writehtml "<tr><td class=programme>The following hack applications are currently running on your TiVo:"
	set shellcmd "$::pslocation"
        if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-about to run ps"}
	set procs [exec $shellcmd ax]
	if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ps run"}
	writehtml "<ul style='margin-top:0.1cm; margin-bottom:0cm' type=disc>"
	set fileitemlist {}
	foreach item $::appsrunning {
		lappend fileitemlist [lindex [split $item "|"] 0]
	}
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-search items >>$fileitemlist<<"}
	foreach appname $fileitemlist {
		if [regexp $appname $procs]  {
			if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-hack found >>$appname<<"}
			foreach item $::appsrunning {
				if {[lindex [split $item "|"] 0] == $appname} {
					set appmessage [lindex [split $item "|"] 1]
					if {$appname == "cron"} {
						set cronactive 1
					}
				}
			}
			writehtml "<li>$appmessage</li>"
		}
	}
	writehtml "</ul></td></tr>"
	
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-hack application test end"}
	
	## parse cron file and list scheduled tasks

	if {$cronactive && $::cronlistrequired} {
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-crontab test start"}
		writehtml "<tr><td class=programme>The following hack applications are scheduled to run on your TiVo:"
		if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-about to parse crontab file"}
		set cronfile [open $::cronloc "r"]
		writehtml "<ul style='margin-top:0.1cm; margin-bottom:0cm' type=disc>"
		set cronitemlist {}
		foreach item $::cronlist {
			lappend cronitemlist [lindex [split $item "|"] 0]
		}
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-search items >>$cronitemlist<<"}
		while { ! [eof $cronfile] } {
			set line [gets $cronfile]
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-line : >>$line<<"}
			foreach cronname $cronitemlist {
				if [regexp $cronname $line] {
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-permitted item found in line : >>$cronname<<"}
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-about to split cron line into parameter items"}
					
		
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-before tab and space manipulation: >>$line<<"}
					set tabloc [string first "\t" $line]
					while {$tabloc != -1 } {
						set line "[string range $line 0 [expr $tabloc - 1]] [string range $line [expr $tabloc + 1] 9999]"
						set tabloc [string first "\t" $line]
					}
					set doublespaceloc [string first "  " $line]
					while {$doublespaceloc != -1 } {
						set line "[string range $line 0 [expr $doublespaceloc - 1]] [string range $line [expr $doublespaceloc + 2] 9999]"
						set doublespaceloc [string first "  " $line]
					}
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-after tab and space manipulation: >>$line<<"}
					
					
					set paramlist [split $line " "]
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-cron split successfully into individual items"}
					if { [lsearch -glob $paramlist #*] != 0 } {
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-this item is valid - not comment"}
						#set paramlist [split $line " "]
						set m [lindex $paramlist 0]
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-minute parameter : >>$m<<"}
						set h [lindex $paramlist 1]
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-hour parameter : >>$h<<"}
						set dom [lindex $paramlist 2]
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-day of month parameter : >>$dom<<"}
						set mon [lindex $paramlist 3]
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-month parameter : >>$mon<<"}
						set dow [lindex $paramlist 4]
						
						set spaceindow [string first " " $dow]
						if {$spaceindow == -1 } {
							set spaceindow [string first "\t" $dow]
						}
						if {$spaceindow != -1 } {
							set extraremainder [string range $dow [expr $spaceindow + 1] 9999]
							set spaceindow [expr $spaceindow - 1]
							set dow [string range $dow 0 $spaceindow]
						}
	
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-day of week parameter : >>$dow<<"}
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-checkpoint 001"}
						
						set m [string trimleft $m 0]
						set h [string trimleft $h 0]
						
						set offsethours [expr round(($::tzoffset/60)/60)]
						set offsetminutes [expr round((((($::tzoffset/60)/60) - $offsethours) * 60) * 100)/100.00 ]
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-offsethours >>$offsethours<<"}
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-offsetminutes >>$offsetminutes<<"}
						
					
						set newm [expr $m + $offsetminutes]
						if {$newm == 60} { 
							set newm 0 
							set offsethours [expr $offsethours + 1]
							if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-offsetminutes - = 60"}
						}
						if {$newm > 60} { 
							set newm [expr $newm - 60]
							set offsethours [expr $offsethours + 1]
							if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-offsetminutes - > 60"}
						}
						if {$newm < 0} { 
							set newm [expr $newm + 60]
							set offsethours [expr $offsethours - 1]
							if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-offsetminutes - < 0"}
						}
						
						set newh [expr $h + $offsethours]
						if {$newh == 24} { set newh 0 }
						if {$newh > 24 } { set newh [expr $newh - 24] }
						if {$newh < 0 } { set newh [expr $newh + 24 ] }						
						
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-timezone related hour adjustment : >>$newh<<"}
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-timezone related minute adjustment : >>$newm<<"}
						
						set h [expr round($newh)]
						set m [expr round($newm)]
						
						catch { unset newh }
						catch { unset newm }
						catch { unset offsethours }
						catch { unset offsetminutes }
						
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-hour parameter now : >>$h<<"}
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-minute parameter now : >>$m<<"}
						
									
						# searching for repetative minute runs
						if { [lsearch -glob $m "*/*"] != -1 } {
						
							if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-checkpoint 002"}
							set mlist [split $m "/"]
							if { $h == "*" } {
								if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-checkpoint 003"}
								set schedout "(Every [lindex $mlist 1] minutes)"
							} 
						
						# searching for repetative hour runs
						} elseif { [lsearch -glob $h "*/*"] != -1 } {
							if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-checkpoint 004"}
							set hlist [split $h "/"]
							if { $m == "*" } {
								if {$m==""} {
									set m "00"
								}
								if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-checkpoint 005"}
								set schedout "(Every [lindex $hlist 1] hours)"
							}
							if {$m==""} {
								set m "00"
							}
							
						# all others
						} else {
						
							if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-checkpoint 006"}
							
							if {$h == "*"} {
							
								set schedout "(hourly - $m minutes past the hour)"
							
							} else {
							
							
								if {[expr $h+($::tzoffset/3600)] < 13} {
									if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-checkpoint 007"}
									set ampm "AM"
								} else {
									if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-checkpoint 008"}
									set ampm "PM"
								}
								if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-checkpoint 008a"}
								
								set dailytext "daily"
								
								# we assume either dom or dow - not both
								
								if {$dom != "*"} {
								
									if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-day of month section"}
								
									set domlist [split $dom "/"]
									if {[lindex $domlist 0] == "*" } {
										set dailytext "every [lindex $domlist 1] days"
									}
									if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-day of month section - a"}
									if {$dailytext == "daily"} {
										set domlist [split $dom "-"]
										if {[lindex $domlist 0] !="*" && [lindex $domlist 0] != "" && [lindex $domlist 1] != ""} {
											set dailytext "on days [lindex $domlist 0] to [lindex $domlist 1] of the month"
										}
									}
									if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-day of month section - b"}
									if {$dailytext == "daily"} {
										set dailytext "every [lindex $domlist 1] days"
									}
									
								} else {
									if {$dow != "*"} {
									
										if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-day of week section"}
										
										if {[string first "/" $dow] != -1} {
									
											set dowlist [split $dow "/"]
											if {[lindex $dowlist 0] == "*" } {
												set dailytext "every [lindex $dowlist 1] weekdays"
											}
										}
										
										if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-day of week section - a"}
										
										if {$dailytext == "daily"} {
											
											if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-day of week section - a - 1"}
										
											set dailytext ""
											set dowlistsuper [split $dow ","]
											set secondtimearound "N"
											
											if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-day of week section - a - 2"}
											
											foreach dowsuper $dowlistsuper {
											
												if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-dow super item: >>$dowsuper<<"}
												
												if { $secondtimearound == "Y" } {
													set dailytext "${dailytext}, "	
													if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-second time around - dailytext >>$dailytext<<"}
										
												}

												if {[string first "-" $dowsuper] != -1} {
												
													if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-dow dashed item identfied"}

													set dowlist [split $dowsuper "-"]
													
													if {[lindex $dowlist 0] !="*" && [lindex $dowlist 0] != "" && [lindex $dowlist 1] != ""} {
														
														set dailytexttemp ""
														
														if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-valid dashed dow item found"}
														if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-first dowlist value >>[lindex $dowlist 0]<<"}
														if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-second dowlist value >>[lindex $dowlist 1]<<"}
														
														switch [lindex $dowlist 0] {
															0	{ set dailytexttemp "Sunday to" }
															1	{ set dailytexttemp "Monday to" }
															2	{ set dailytexttemp "Tuesday to" }
															3	{ set dailytexttemp "Wednesday to" }
															4	{ set dailytexttemp "Thursday to" }
															5	{ set dailytexttemp "Friday to" }
															6	{ set dailytexttemp "Saturday to" }
															7	{ set dailytexttemp "Sunday to" }
															default	{ set dailytexttemp "" }
														}
														
														switch [lindex $dowlist 1] {
															0	{ set dailytexttemp "$dailytexttemp Sunday" }
															1	{ set dailytexttemp "$dailytexttemp Monday" }
															2	{ set dailytexttemp "$dailytexttemp Tuesday" }
															3	{ set dailytexttemp "$dailytexttemp Wednesday" }
															4	{ set dailytexttemp "$dailytexttemp Thursday" }
															5	{ set dailytexttemp "$dailytexttemp Friday" }
															6	{ set dailytexttemp "$dailytexttemp Saturday" }
															7	{ set dailytexttemp "$dailytexttemp Sunday" }
															default	{ set dailytexttemp "$dailytexttemp" }
														}
														
														switch $dailytexttemp {
															"Sunday to Saturday"	{ set dailytexttemp "daily" }
															"Monday to Sunday"	{ set dailytexttemp "daily" }
															"Monday to Friday"	{ set dailytexttemp "weekdays" }
															default			{ set dailytexttemp "$dailytexttemp" }
														}										
														set dailytext "${dailytext}${dailytexttemp}"
														if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]- dashed dow item section - dailytext >>$dailytext<<"}
													}	
												} else {
													if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-non dashed dow item identified"}
													if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-dow super value >>$dowsuper<<"}
													switch $dowsuper {
														0	{ set dailytext "${dailytext}Sunday" }
														1	{ set dailytext "${dailytext}Monday" }
														2	{ set dailytext "${dailytext}Tuesday" }
														3	{ set dailytext "${dailytext}Wednesday" }
														4	{ set dailytext "${dailytext}Thursday" }
														5	{ set dailytext "${dailytext}Friday" }
														6	{ set dailytext "${dailytext}Saturday" }
														7	{ set dailytext "${dailytext}Sunday" }
														default	{ set dailytext "${dailytext}" }
													}																					
													if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-non dashed dow item section - dailytext >>$dailytext<<"}
												}
												set secondtimearound "Y"
											}
											if {$dailytext == ""} {
												set dailytext "daily"
												if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-dailytext blank - so reset to daily"}														
											}	
										}
									}
								}
								
								set monthlytext ""

								if {$mon != "*"} {

									set monlistsuper [split $mon ","]
									set secondtimearound "N"

									foreach monsuper $monlistsuper {

										if { $secondtimearound == "Y" } {
											set monthlytext "${monthlytext}, "	
										}

										if {[string first "-" $monsuper] != -1} {

											set monlist [split $monsuper "-"]

											if {[lindex $monlist 0] !="*" && [lindex $monlist 0] != "" && [lindex $monlist 1] != ""} {

												set monthlytexttemp ""
												
												switch [lindex $monlist 0] {
													1	{ set monthlytexttemp "January to" }
													2	{ set monthlytexttemp "February to" }
													3	{ set monthlytexttemp "March to" }
													4	{ set monthlytexttemp "April to" }
													5	{ set monthlytexttemp "May to" }
													6	{ set monthlytexttemp "June to" }
													7	{ set monthlytexttemp "July to" }
													8	{ set monthlytexttemp "August to" }
													9	{ set monthlytexttemp "September to" }
													10	{ set monthlytexttemp "October to" }
													11	{ set monthlytexttemp "November to" }
													12	{ set monthlytexttemp "December to" }
													default	{ set monthlytexttemp "" }
												}

												switch [lindex $monlist 1] {
													1	{ set monthlytexttemp "$monthlytexttemp January" }
													2	{ set monthlytexttemp "$monthlytexttemp February" }
													3	{ set monthlytexttemp "$monthlytexttemp March" }
													4	{ set monthlytexttemp "$monthlytexttemp April" }
													5	{ set monthlytexttemp "$monthlytexttemp May" }
													6	{ set monthlytexttemp "$monthlytexttemp June" }
													7	{ set monthlytexttemp "$monthlytexttemp July" }
													8	{ set monthlytexttemp "$monthlytexttemp August" }
													9	{ set monthlytexttemp "$monthlytexttemp September" }
													10	{ set monthlytexttemp "$monthlytexttemp October" }
													11	{ set monthlytexttemp "$monthlytexttemp November" }
													12	{ set monthlytexttemp "$monthlytexttemp December" }
													default	{ set monthlytexttemp "$monthlytexttemp" }
												}
												
												set monthlytext "${monthlytext}${monthlytexttemp}"

											}

										} else {
										
										
											switch $monsuper {
												1	{ set monthlytext "${monthlytext}January" }
												2	{ set monthlytext "${monthlytext}February" }
												3	{ set monthlytext "${monthlytext}March" }
												4	{ set monthlytext "${monthlytext}April" }
												5	{ set monthlytext "${monthlytext}May" }
												6	{ set monthlytext "${monthlytext}June" }
												7	{ set monthlytext "${monthlytext}July"}
												8	{ set monthlytext "${monthlytext}August" }
												9	{ set monthlytext "${monthlytext}September" }
												10	{ set monthlytext "${monthlytext}October" }
												11	{ set monthlytext "${monthlytext}November" }
												12	{ set monthlytext "${monthlytext}December" }
												default	{ set monthlytext "${monthlytext}" }
											}
										}

										set secondtimearound "Y"
									}

								}
								
								if {$monthlytext != ""} {
									if {$dailytext != ""} {
										set dailytext "$dailytext - $monthlytext"
									} else {
										set dailytext "$monthlytext"
									}
									set monthlytext ""
								}
						
								if {$m<10} {
									set m "0$m"
								}
								if {$m=="" || $m=="0"} {
									set m "00"
								}
									
								if {$::yankspeak} {
									set schedout "($h:$m$ampm ${dailytext})"
								} else {
									if {$h == 24} {
										set schedout "(00:$m ${dailytext})"
									} else {
										if {$h < 10} {
											set schedout "(0$h:$m ${dailytext})"
										} else {
											set schedout "($h:$m ${dailytext})"
										}
									}
								}
								if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-schedout line >>$schedout<<"}
								
							}
								
								
						}
						
						foreach item $::cronlist {
							if {[lindex [split $item "|"] 0] == $cronname} {
								set appmessage "[lindex [split $item "|"] 1] $schedout"
							}
						}
						
						writehtml "<li>$appmessage</li>"
					} else {
						if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-invalid cron line >>$line<<"}
					}
				}
			}
		}
		writehtml "</ul></td></tr>"
		
		close $cronfile
	
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-crontab test end"}
		# ip information
		
		if { $::externalipsetting } {
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-external IP info start"}
			writehtml "<tr><td class=programme>"
			if {$::ouripaddress != ""} {
				writehtml "External IP address: $::ouripaddress"
			} else {
				writehtml "External IP address unknown!"
			}
			writehtml "</tr></td>"
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-external IP info end"}
		}	
		
	}
	
	# clear down variables 	
	foreach var [info vars] {
		catch {
			if {$var != "itemsFound"} {
				if { [catch { 
					if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-unsetting variable >>$var<<"}
				} fid] } {
					# null
				} else {
					if { [catch { 
						unset $var  
					} fid] } {
						if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-error in unsetting variable >>$var<<"}
					} 
				}
			}
		}
	}

}



############################################################################################################################################
## CHECKING DISK STATUS

proc disk_status {} {

	set cumulativediff 0
	set cumulativediffcount 0
	after 2000
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-disk status - started"}
  	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-disk status - version >>$::version<<"}
  	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-disk status - dtivo >>$::dtivo<<"}
	set list [list]
	store_space space time count list 103 0 0
	store_space space time count list 203 0 0
	store_space space time count list 204 0 0
  	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-disk status - checkpoint #1"}
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-disk status - /Recording/DiskUsed/10"}
	ForeachMfsFileTrans fsid name type "/Recording/DiskUsed/10" "" 15 {
		set rec [db $::db openid $fsid]
		if { [ catch { 
			set showing [dbobj $rec get Showing]
			set program [dbobj $showing get Program]
			set title [strim [dbobj $program get Title]]
			if {$::version >= 3} {
				set recbeh [dbobj $rec get RecordingBehavior]
				set seltype [dbobj $recbeh get PresentationBehavior]
			} else {
				set seltype [dbobj $rec get SelectionType]
			}
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-title >>$title<< | sel type >>$seltype<<"}
		} fid] } {
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Item Ignored - /Recording/DiskUsed/10 - Main Section >>$fid<<"}
		} 
		scan $name "%d:%d" fsid streamsize
		set state ""
		if { [ catch { set state [dbobj $rec get State] } fid] } {
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Item Ignored  - /Recording/DiskUsed/10 - State Section >>$fid<<"}
		}
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-state >>$state<<"}
		if { $state != "" } {
			set recquality [dbobj $rec get RecordQuality]
			set recdur [rec_get_dur $rec]
			if {$state == 5} {
				# program deleted
				store_space space time count list 102 $streamsize $recdur
			} else {
				# program not deleted
				set expsecs [timedateconv $rec Expiration]
				if {$expsecs < [clock seconds] && $seltype != 6 && $state == 4} {
					#expired non suggestion
					set seltype -$seltype
					store_space space time count list $seltype $streamsize $recdur
				} elseif {$expsecs < [clock seconds] && $seltype == 6} {
					# expired suggestion
					store_space space time count list 204 $streamsize $recdur
				} elseif {$expsecs >= [clock seconds] && $seltype == 6} {
					# suggestion that is not expired
					store_space space time count list 203 $streamsize $recdur
				} else {	
					# the rest
					store_space space time count list $seltype $streamsize $recdur
				}
				if { [expr round($recdur/60) ] > 25 } {
					set actbitrate -1
					set expbitrate -1
					catch {
						set actbitrate  [expr (round(((($streamsize * 8) / $recdur) * 1024) / 10000)) * 10000]
						switch $recquality {
							100		{ set expbitrate 5960000 }
							75		{ set expbitrate 3660000 }
							40		{ set expbitrate 2760000 }
							0		{ set expbitrate [expr $uktivo ? 1700000 : 1630000] }
							default		{ set expbitrate 5960000 }
						}
						set expsize [ expr (($recdur * ($expbitrate / 1024)) / 8) / 1024 ]
						set actsize [ expr $streamsize / 1024]
						set sizediff [ expr $actsize - $expsize]
						set sizepercdiff [ expr (($sizediff * 1.0000) / ($expsize * 1.0000)) * 100.0 ]
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Actual bitrate : >>$actbitrate<<"}
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Expected bitrate : >>$expbitrate<<"}
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Bitrate difference: >>[ expr $expbitrate - $actbitrate]<<"}
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Item duration : >>[expr round($recdur/60) ]<<"}
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Specified record quality : >>$recquality<<"}	
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Actual Size : >>$actsize Mb<<"}
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Expected Size : >>$expsize Mb<<"}	
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Size Variance : >>$sizediff Mb<< : >>$sizepercdiff %<<"}	
						if {$sizepercdiff != 0} {
							set cumulativediff [ expr $cumulativediff + $sizepercdiff ]
							set cumulativediffcount [ expr $cumulativediffcount + 1]
						}
					}
					catch { unset actbitrate }
					catch { unset expbitrate }
					catch { unset expsize }
					catch { unset actsize }
					catch { unset sizediff }
					catch { unset sizepercdiff }
				}

			}
		}
	}
	after 2000
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-disk status - checkpoint #3"}
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-disk status - /Recording/DiskUsed/11"}
	ForeachMfsFileTrans fsid name type "/Recording/DiskUsed/11" "" 15 {
		set rec [db $::db openid $fsid]
		if { [ catch { 
			set showing [dbobj $rec get Showing]
			set program [dbobj $showing get Program]
			set title [strim [dbobj $program get Title]]
			if {$::version >= 3} {
				set recbeh [dbobj $rec get RecordingBehavior]
				set seltype [dbobj $recbeh get PresentationBehavior]
			} else {
				set seltype [dbobj $rec get SelectionType]
			}
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-title >>$title<< | sel type >>$seltype<<"}
		} fid] } {
		 	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Item Ignored - /Recording/DiskUsed/11 - Main Section >>$fid<<"}
		} 
		scan $name "%d:%d" fsid streamsize
		set state ""
		if { [ catch {  set state [dbobj $rec get State] } fid] } {
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Item Ignored - /Recording/DiskUsed/11 - State Section >>$fid<<"}
		}
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-state >>$state<<"}
		if { $state != "" } {
			set recquality [dbobj $rec get RecordQuality]
			set recdur [rec_get_dur $rec]
		        if {$state == 5} {
		        	# program deleted
		        	store_space space time count list 102 $streamsize $recdur
			} else {
				# program not deleted
				set expsecs [timedateconv $rec Expiration]
				if {$expsecs < [clock seconds] && $seltype != 6} {
					#expired non suggestion
					set seltype -$seltype
					store_space space time count list $seltype $streamsize $recdur
				} elseif {$expsecs < [clock seconds] && $seltype == 6} {
					# expired suggestion
					store_space space time count list 204 $streamsize $recdur
				} elseif {$expsecs >= [clock seconds] && $seltype == 6} {
					# suggestion that is not expired
					store_space space time count list 203 $streamsize $recdur
				} else {	
					# the rest
					store_space space time count list $seltype $streamsize $recdur
				}
				if { [expr round($recdur/60) ] > 25 } {
					set actbitrate -1
					set expbitrate -1
					catch {
						set actbitrate  [expr (round(((($streamsize * 8) / $recdur) * 1024) / 10000)) * 10000]
						switch $recquality {
							100		{ set expbitrate 5960000 }
							75		{ set expbitrate 3660000 }
							40		{ set expbitrate 2760000 }
							0		{ set expbitrate [expr $uktivo ? 1700000 : 1630000] }
							default		{ set expbitrate 5960000 }
						}
						set expsize [ expr (($recdur * ($expbitrate / 1024)) / 8) / 1024 ]
						set actsize [ expr $streamsize / 1024]
						set sizediff [ expr $actsize - $expsize]
						set sizepercdiff [ expr (($sizediff * 1.0000) / ($expsize * 1.0000)) * 100.0 ]
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Actual bitrate : >>$actbitrate<<"}
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Expected bitrate : >>$expbitrate<<"}
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Bitrate difference: >>[ expr $expbitrate - $actbitrate]<<"}
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Item duration : >>[expr round($recdur/60) ]<<"}
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Specified record quality : >>$recquality<<"}	
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Actual Size : >>$actsize Mb<<"}
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Expected Size : >>$expsize Mb<<"}	
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Size Variance : >>$sizediff Mb<< : >>$sizepercdiff %<<"}	
						if {$sizepercdiff != 0} {
							set cumulativediff [ expr $cumulativediff + $sizepercdiff ]
							set cumulativediffcount [ expr $cumulativediffcount + 1]
						}
					}
					catch { unset actbitrate }
					catch { unset expbitrate }
					catch { unset expsize }
					catch { unset actsize }
					catch { unset sizediff }
					catch { unset sizepercdiff }
				}
			}
		}
	}
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-disk status - checkpoint #4"}
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-disk status - /DiskUsed"}
	ForeachMfsFileTrans fsid name type "/DiskUsed" "" 15 {
		set rec [db $::db openid $fsid]
		if { [ catch { 
			set showing [dbobj $rec get Showing]
			set program [dbobj $showing get Program]
			set title [strim [dbobj $program get Title]]
			if {$::version >= 3} {
				set recbeh [dbobj $rec get RecordingBehavior]
				set seltype [dbobj $recbeh get PresentationBehavior]
			} else {
				set seltype [dbobj $rec get SelectionType]
			}
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-title >>$title<< | sel type >>$seltype<<"}
		} fid] } {
		 	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Item Ignored - /DiskUsed - Main Section >>$fid<<"}
		} 
		scan $name "%d:%d:%d:%d" spacetype junk streamsize fsid
		set state ""
		if { [ catch {  set state [dbobj $rec get State] } fid] } {
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Item Ignored - /DiskUsed - State Section >>$fid<<"}
		}
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-state >>$state<<"}
		if { $state != "" } {
			set recquality [dbobj $rec get RecordQuality]
			set recdur [rec_get_dur $rec]
			if {$state == 5} {
				# program deleted
				store_space space time count list 102 $streamsize $recdur
			} else {
				# program not deleted
				set expsecs [timedateconv $rec Expiration]
				if {$expsecs < [clock seconds] && $seltype != 6} {
					#expired non suggestion
					set seltype -$seltype
					store_space space time count list $seltype $streamsize $recdur
				} elseif {$expsecs < [clock seconds] && $seltype == 6} {
					# expired suggestion
					store_space space time count list 204 $streamsize $recdur
				} elseif {$expsecs >= [clock seconds] && $seltype == 6} {
					# suggestion that is not expired
					store_space space time count list 203 $streamsize $recdur
				} else {	
					# the rest
					store_space space time count list $seltype $streamsize $recdur
				}
				if { [expr round($recdur/60) ] > 25 } {
					set actbitrate -1
					set expbitrate -1
					catch {
						set actbitrate  [expr (round(((($streamsize * 8) / $recdur) * 1024) / 10000)) * 10000]
						switch $recquality {
							100		{ set expbitrate 5960000 }
							75		{ set expbitrate 3660000 }
							40		{ set expbitrate 2760000 }
							0		{ set expbitrate [expr $uktivo ? 1700000 : 1630000] }
							default		{ set expbitrate 5960000 }
						}
						set expsize [ expr (($recdur * ($expbitrate / 1024)) / 8) / 1024 ]
						set actsize [ expr $streamsize / 1024]
						set sizediff [ expr $actsize - $expsize]
						set sizepercdiff [ expr (($sizediff * 1.0000) / ($expsize * 1.0000)) * 100.0 ]
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Actual bitrate : >>$actbitrate<<"}
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Expected bitrate : >>$expbitrate<<"}
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Bitrate difference: >>[ expr $expbitrate - $actbitrate]<<"}
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Item duration : >>[expr round($recdur/60) ]<<"}
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Specified record quality : >>$recquality<<"}	
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Actual Size : >>$actsize Mb<<"}
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Expected Size : >>$expsize Mb<<"}	
						if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Size Variance : >>$sizediff Mb<< : >>$sizepercdiff %<<"}	
						if {$sizepercdiff != 0} {
							set cumulativediff [ expr $cumulativediff + $sizepercdiff ]
							set cumulativediffcount [ expr $cumulativediffcount + 1]
						}
					}
					catch { unset actbitrate }
					catch { unset expbitrate }
					catch { unset expsize }
					catch { unset actsize }
					catch { unset sizediff }
					catch { unset sizepercdiff }
				}
			}
		}
	}
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-disk status - checkpoint #5"}
	after 2000
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-disk status - checkpoint #6"}
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-disk status -recording in progress"}
	ForeachMfsFileTrans fsid name type "/Recording/InProgress" "" 15 {
		set rec [db $::db openid $fsid]
		if { [ catch { 
			set showing [dbobj $rec get Showing]
			set program [dbobj $showing get Program]
			set title [strim [dbobj $program get Title]]
			if {$::version >= 3} {
				set recbeh [dbobj $rec get RecordingBehavior]
				set seltype [dbobj $recbeh get PresentationBehavior]
			} else {
				set seltype [dbobj $rec get SelectionType]
			}
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-title >>$title<< | sel type >>$seltype<<"}
		} fid] } {
		 	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Item Ignored - /Recording/InProgress - Main Section >>$fid<<"}
		} 
		set indexpath [dbobj $rec get IndexPath]
		if {[string match "*LiveCache*" $indexpath]} {
			set parts [dbobj $rec gettarget Part]
			if {$::dtivo} {
				set size [expr [llength $parts] * 256 * 1024] 
			} else {
				set size [expr [llength $parts] * 204 * 1024] 
			}
			set secs [expr round($size / (5960000.0/8/1024))]
			store_space space time count list 100 $size $secs
		} else {
			set parts [dbobj $rec get Part]
			set size [expr [llength $parts] * 512 * 1024] 
			set secs 0
			foreach part $parts {
				set begin [dbobj $part get Begin]
				set end [dbobj $part get End]
				if {$end != "" && $begin != ""} {
					set diff [expr ($end - $begin)/1000]
					incr secs $diff
				}
			}
			store_space space time count list 101 $size $secs
		}
	}	
	
	
	if {$cumulativediffcount > 0} {
		set cumulativediff [ expr ((round ($cumulativediff * 10)) / 10.0) / ($cumulativediffcount * 1.0) ]
	} else {
		set cumulativediff 0
	}
	
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-disk status - average difference between expected and actual size : >>$cumulativediff %<<"}
	set ::spacevariance $cumulativediff
	
	catch { unset cumulativediff }
	catch { unset cumulativediffcount }
	
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-disk status - checkpoint #7"}
	if {[info exists space]} {
    		set list [lsort -integer $list]
    		set tcount 0
    		set tspace 0
    		set ttime 0
    		set sugtspace 0
    		set exptspace 0
    		set expsugtspace 0
    		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-disk status - checkpoint #8"}
		foreach type $list {
			if {$type < 102} {
				if {$type  >= 0} {
					incr tcount $count($type)
					incr tspace $space($type)
					incr ttime  $time($type)
				}
			}
			if {$type == 203} {
				# suggestions 
				incr sugtspace $space($type)
			}
		  	if {$type == 204} {
		  		# suggestions 
		  		incr expsugtspace $space($type)
			}
			if {$type < 0} {
				# expired - not including suggestions
				incr exptspace $space($type)
			}
		}
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-disk status - checkpoint #9"}
    		
    		############
    		
    		set ::spacedetail "Space usage breakdown: \n"
    		set ::spacepopdetail "Space usage breakdown: \\r\\n"
     		set selectiontypes "{Show Recommendation} {Package Recommendation} {By Name} {By Channel} Manual {Suggestion} {Fuzzy Package} Bookmark {Season Pass} {Manual Season Pass} Guide IPreview {Wish List} Extended {Manual Extended} {Capture Request}"
  		set presentationbehtypes "Single {Season Pass} {Wish List} {Watch Only} {Tivo Clips} Suggestion {Tivo Clips Suggestion} Invisible {Manual Season Pass} Manual {Cache History}"    		
    		set type 1
    		set rollingsum 0
    		while {$type <= 16} {
    			set ourspace 0
    			set ourtemptype ""
    			if {$::version >= 3} {
    				set ourtemptype [lindex $presentationbehtypes [expr $type-1] ]
    			} else {
    				set ourtemptype [lindex $selectiontypes [expr $type-1] ]
    			}
    			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-TYPE: $ourtemptype"}
    			catch {
				set ourspace $space($type)
			}
			if {$ourspace > 0} {
				incr rollingsum $ourspace
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-($type) $ourtemptype = [expr $ourspace / 1024] MB ([expr $rollingsum / 1024] MB)."}
				append ::spacedetail "- $ourtemptype : [expr $ourspace / 1024] Mb \n"
				append ::spacepopdetail "- $ourtemptype : [expr $ourspace / 1024] Mb \\r\\n"
			}
    			set ourspace 0
    			catch {
				set ourspace $space([expr $type * -1])
			}
			if {$ourspace > 0} {
				incr rollingsum $ourspace
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-($type) Expired $ourtemptype = [expr $ourspace / 1024] MB ([expr $rollingsum / 1024] MB)."}
				append ::spacedetail "- Expired $ourtemptype : [expr $ourspace / 1024] Mb \n"
				append ::spacepopdetail "- Expired $ourtemptype : [expr $ourspace / 1024] Mb \\r\\n"
			}
    			incr type 1
    		}
    		set ourspace 0
    		catch {
			set ourspace $space(203)
		}
    		incr rollingsum $ourspace
    		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-(O) Suggestions = [expr $ourspace / 1024] MB ([expr $rollingsum / 1024] MB)."}
    		if { $ourspace > 0 } {
    			append ::spacedetail "- Suggestions : [expr $ourspace / 1024] Mb \n"
    			append ::spacepopdetail "- Suggestions : [expr $ourspace / 1024] Mb \\r\\n"
    		}
		set ourspace 0
    		catch {
			set ourspace $space(204)
		}
    		incr rollingsum $ourspace
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-(O) Expired Suggestions = [expr $ourspace / 1024] MB ([expr $rollingsum / 1024] MB)."}
    		if { $ourspace > 0 } {
    			append ::spacedetail "- Expired Suggestions : [expr $ourspace / 1024] Mb \n"
    			append ::spacepopdetail "- Expired Suggestions : [expr $ourspace / 1024] Mb \\r\\n"
    		}
    		set ourspace 0
    		catch {
			set ourspace $space(101)
		}
    		catch {
			set ourspace $space(100)
		}
    		incr rollingsum $ourspace
		if { $::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-(O) Live Cache = [expr $ourspace / 1024] MB ([expr $rollingsum / 1024] MB)."}
    		if { $ourspace > 0 } {
    			append ::spacedetail "- Live Cache : [expr $ourspace / 1024] Mb \n"
    			append ::spacepopdetail "- Live Cache : [expr $ourspace / 1024] Mb \\r\\n"
    		}
    		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-(-) TOTAL = [expr $rollingsum / 1024] MB."}
    		if { $rollingsum > 0 } {
    			append ::spacedetail "- Total : [expr $rollingsum / 1024] Mb \n"
    			append ::spacepopdetail "- Total : [expr $rollingsum / 1024] Mb \\r\\n"
    			append ::spacedetail "- Real % Used : [expr ( round ( ( ( ( $rollingsum / 1024 ) * 1.000) / ( $::usersize * 1.000) ) * 1000) ) / 10.0 ] %"
			append ::spacepopdetail "- Real % Used : [expr ( round ( ( ( ( $rollingsum / 1024 ) * 1.000) / ( $::usersize * 1.000) ) * 1000) ) / 10.0 ] %"    		
    		}		
    			
    		set spaceusedbysuggestionsmeg [expr round($sugtspace/1024)]
    		set spaceusedbyexpiredsuggestionsmeg [expr round($expsugtspace/1024)]
    		set spaceusedbyexpiredmeg [expr round($exptspace/1024)]
    		
    		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-(O) Un-Expired suggestions = $spaceusedbysuggestionsmeg MB"}
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-(O) Expired suggestions = $spaceusedbyexpiredsuggestionsmeg MB"}
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-(O) Expired items = $spaceusedbyexpiredmeg MB"}
	
		if {$::expiredsuggestionstreatment == "S"} {
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-expired suggestions are classified suggestions"}
    			set spaceusedbysuggestionsmeg [expr $spaceusedbysuggestionsmeg + $spaceusedbyexpiredsuggestionsmeg]
    		} elseif {$::expiredsuggestionstreatment == "E"} {
    			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-expired suggestions are classified expired items"}
    			set spaceusedbyexpiredmeg [expr $spaceusedbyexpiredmeg + $spaceusedbyexpiredsuggestionsmeg]
    		} else {
    			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-expired suggestions are classified suggestions"}
    			set spaceusedbysuggestionsmeg [expr $spaceusedbysuggestionsmeg + $spaceusedbyexpiredsuggestionsmeg]
    		}
    		
    		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-space used by classified suggestions = $spaceusedbysuggestionsmeg meg"}
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-space used by classified expired items = $spaceusedbyexpiredmeg meg"}
	
    		
    		
    		set ::corespaceusedmeg [expr round($tspace/1024)]
    		set interpretedspaceusedmeg 0
    		if {$::countsuggestionsasfreespace && $::countexpiredasfreespace} {
    			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-suggestions & expired are free space"}
    			set interpretedspaceusedmeg  $::corespaceusedmeg
    			set interpretedotherspacemeg [expr $spaceusedbysuggestionsmeg + $spaceusedbyexpiredmeg]
    		} else {
    			if {$::countsuggestionsasfreespace} {
    				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-suggestions are free space - expired items are used space"}
  	    			set interpretedspaceusedmeg  [expr $::corespaceusedmeg + $spaceusedbyexpiredmeg]
    				set interpretedotherspacemeg $spaceusedbysuggestionsmeg  			
    			} elseif {$::countexpiredasfreespace} {
    				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-expired items are free space - suggestions are used space"}
  	    			set interpretedspaceusedmeg  [expr $::corespaceusedmeg + $spaceusedbysuggestionsmeg]
    				set interpretedotherspacemeg $spaceusedbyexpiredmeg
    			} else {
    				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-suggestions & expired items are used space"}
   	    			set interpretedspaceusedmeg  [expr $::corespaceusedmeg + $spaceusedbysuggestionsmeg + $spaceusedbyexpiredmeg ]
    				set interpretedotherspacemeg 0	
    			}
    		}
    		
    		set interpretedfreespacemeg [expr $::usersize - $interpretedspaceusedmeg]
    		set interpretedpercentused [expr ((($interpretedspaceusedmeg*1.0000) / ($::usersize*1.0000))*100.00)]
 
	}
	
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-disk status - checkpoint #10"}
	
	set ::actualdrivespacemeg  [expr round($::usersize)]
	set ::actualdrivespacegig  [expr round(($::usersize/1024) * 10) / 10.0]
	
	set ::actualspaceusedmeg [expr round($interpretedspaceusedmeg)]
	set ::actualspaceusedgig [expr round(($interpretedspaceusedmeg/1024) * 10) / 10.0]
	
	set ::actualspacefreemeg [expr round($interpretedfreespacemeg)]
	set ::actualspacefreegig [expr round(($interpretedfreespacemeg/1024) * 10) / 10.0]
	
	set ::otherspacemeg [expr round($interpretedotherspacemeg)]
	set ::otherspacegig [expr round(($interpretedotherspacemeg/1024) * 10) / 10.0]
	
	set ::actualpercentused [expr round($interpretedpercentused * 100) / 100.00]
	set ::actualpercentfree [expr 100.00 - $::actualpercentused]
	set ::otherpercent [expr round((((($interpretedotherspacemeg*1.0000) / ($::usersize*1.0000))*100.00)) * 100) / 100.00]
	
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-core space used = $::corespaceusedmeg meg"}
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-actual drive space = $::actualdrivespacemeg meg"}
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-actual space used = $::actualspaceusedmeg meg"}
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-actual space free = $::actualspacefreemeg meg"}
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-other space = $::otherspacemeg meg"}
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-actual percent used = $::actualpercentused %"}
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-actual percent free = $::actualpercentfree %"}
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-other percent = $::otherpercent %"}
	
	# clear down variables 	
	foreach var [info vars] {
		catch {
			if {$var != "actualpercentused"} {
				if { [catch { 
					if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-unsetting variable >>$var<<"}
				} fid] } {
					# null
				} else {
					if { [catch { 
						unset $var  
					} fid] } {
						if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-error in unsetting variable >>$var<<"}
					} 
				}
			}
		}
	}
	
  	return $::actualpercentused
}



proc timedateconv {obj what} { 
	return [expr [dbobj $obj get ${what}Date]*86400+[dbobj $obj get ${what}Time]]
}          


proc timeconv {time} {
	return [format "%d:%02d:%02d" [expr ($time/(60*60))] [expr ($time/60)%60] [expr $time%60]]
}



proc get_type {type} {

	if {$type == 100} {
		set name "Live Cache"
	} elseif {$type == 101} {
		set name "In Progress"
	} elseif {$type == 102} {
		set name "(Deleted Shows)"
	} else {
		if {$type < 0} {
			set name "Expired "
			set type [expr abs($type)]
		} else {
			set name ""
		}
		if {$::version >= 3} {
			set name "$name[strim [lindex $::presentationbehtypes [expr $type - 1]]]"
		} else {
			set name "$name[strim [lindex $::selectiontypes [expr $type - 1]]]"
		}
	}
	catch {unset type }
	return $name
	catch {unset name }
}

proc rec_get_dur {rec} {

	set objtype [dbobj $rec type]
	if {$objtype == "VideoClip"} {
		return 0
	}
	set showing [dbobj $rec get Showing]
	set stopdate [dbobj $rec get StopDate]
	set stoptime [dbobj $rec get StopTime]
	if { $stoptime == "" } {
		set stoptime [expr ([dbobj $showing get Time] + [dbobj $showing get Duration]) % 86400]
	}
	set startdate [dbobj $rec get StartDate]
	set starttime 0
	set starttime [dbobj $rec get StartTime]
	if { $starttime == "" } {
		set starttime [dbobj $showing get Time]
	}
	if {$starttime == ""} {
		set starttime 0
	}	
	if { $stopdate != "" } {
		set durationsecs [expr ($stopdate * 86400 + $stoptime) - ($startdate * 86400 + $starttime)]
	}
	set showingdurationsecs [dbobj $showing get Duration]
	if { $durationsecs == 0 } {
		set durationsecs $showingdurationsecs
	}
	
	catch { unset rec }
	catch { unset stopdate }
	catch { unset stoptime }
	catch { unset startdate }
	catch { unset starttime }
	catch { unset showing }
	catch { unset type }
	return $durationsecs
	catch { unset durationsecs }
}

proc store_space {spacevar timevar countvar listvar rectype streamsize rectime} {

	upvar $spacevar space
	upvar $timevar time
	upvar $countvar count
	upvar $listvar list
	
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-store space: rectype: >>$rectype<<"}
	    
	if {[info exists space($rectype)]} {
		incr space($rectype) $streamsize
		incr time($rectype) $rectime
		incr count($rectype)
	} else {
		lappend list $rectype
		set space($rectype) $streamsize
		set time($rectype) $rectime
		set count($rectype) 1
	}
	
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-stream size>>$streamsize<<"}
        	
}


proc get_totalsizes {} {

	set retval [catch {set getspace [exec "$::getspacelocname"]} error]
	if {$retval != 1} {
		scan $getspace "%*d %*d %d %*d" totalmedia
	} else {
		error $error
	}
	set ::usersize [expr round($totalmedia/2/1024)]
}

## END OF DISK STATUS CODE 
#############################################################################################################################


#############################################################################################################################
## MAIL CHECK CODE 

proc checkmail {} {

	set showdeleted ""
	set gotmail false
	set now     [clock seconds]
	set nowdate [expr $now / 86400]
	set nowtime [expr $now % 86400]
	after 2000
	foreach section {PreTivoCentral MessageBoard} {
		ForeachMfsFileTrans fsid name type "/MessageItem/$section" "" 20 {
			catch {
				set msg [db $::db openid $fsid]
				set dateread [dbobj $msg get DateRead]
				if {$dateread == ""} {
					set from [htmlEncode [dbobj $msg get From]]
					set subject [htmlEncode [dbobj $msg get Subject]]
					set body [htmlEncode [dbobj $msg get Body]]
					set date [dbobj $msg get DateGenerated]
					set time [dbobj $msg get TimeGenerated]
					set seconds [expr $date * 86400 + $time + $::tzoffset]
					if {$::uktivo} {
						set daystr [nth [clock format $seconds -format "%e"]]
						set datestr [clock format $seconds -format "%a $daystr %b %Y"]
					} else {
						set datestr [clock format $seconds -format "%1m/%1d"]
					}
					set expdate [dbobj $msg get ExpirationDate]
					set expsecs [expr $expdate * 86400 + $::tzoffset]
					if {$::uktivo} {
						set daystr [nth [clock format $expsecs -format "%e"]]
						set expdatestr [clock format $expsecs -format "%a $daystr %b %Y"]
					} else {
						set expdatestr [clock format $expsecs -format "%1m/%1d"]
					}
					set deleted [dbobj $msg get Deleted]
					dbobj $msg set DateRead $nowdate
					dbobj $msg set TimeRead $nowtime
					set gotmail true
				}
			}
			catch { unset msg }
		}
  	}
  	catch { unset showdeleted }
	catch { unset now }
	catch { unset gowdate }
	catch { unset nowtime }
	catch { unset daystr }
	catch { unset expdatestr }
	catch { unset deleted }
	catch { unset from }
	catch { unset subject }
	catch { unset body }
	catch { unset date }
	catch { unset time }
	catch { unset seconds }
	catch { unset dateread }
  	return $gotmail
  	catch { unset gotmail }
}


proc htmlEncode { text } {
	set ret "$text"
	regsub -all "\&" $ret {\&amp;} ret
	regsub -all "<" $ret {\&lt;} ret
	regsub -all ">" $ret {\&gt;} ret
	regsub -all "\n" $ret {<BR>} ret
	catch { unset text }
	return "$ret"
	catch { unset ret }
}

## END OF CHECK CODE
#############################################################################################################################


##############################################################################################################################
## HISTORY code for record list

proc recordhistory {} {

	set itemsFound 0
	set colourtoggle 1
	set cancelreasons "SwitchToLiveTv RecordDifferentShowing StayOnLiveTv InternalError PowerWasOff Expired GotBetterSuggestion DemoMode UnexpectedConflict UserRequestedRecording UserRequestedSeasonPass ExplicitlyDeleted ChannelLineupChanged ProgramGuideChanged RecorderEmergency UserCancelledSeasonPass FuzziesTurnedOff FuzzyStoppedEarly Unknown ProgramSourceConflict ConvertedLiveCache LiveCacheOnlySuccessful ProgramSourceDiskConflict ExplicitlyDeletedFromToDo ProgramSourceModified NotAuthorized NoReRecord NoSignal MaxRecordingsExceeded CaptureRequestExpired NoSignalTunerOne NoSignalTunerTwo MaxRecordingsNowShowing VideoMgrDeniedTuner"
	set now [clock seconds]
	set oldday ""
	if { $::rejectedrecreq == -1 || $::rejectedrecreq == 0 } {
		set mintime [expr $now - $::dmailHoursahead * 3600]
	} else {
		set mintime $now
	}
	if { $::rejectedrecreq == 1 || $::rejectedrecreq == 0 } {
		set maxtime [expr $now + $::dmailHoursahead * 3600]
	} else {
		set maxtime $now
	}
	set afterbefore true
	set werebefore false
	after 2000
	ForeachMfsFile fsid name type "/Recording/History" "" {
		set recdate [split $name ":"]
		regsub {^(-?)0+([1-9])} [lindex $recdate 1] {\1\2} rectime
		set rectime [expr [lindex $recdate 0] * 86400 + $rectime]
		if {$rectime > $mintime && $rectime < $maxtime} {
			if {$::debuglvl>2} { puts "## new program "}
			RetryTransaction {
				set rec [db $::db openid $fsid ]
				set creason [dbobj $rec get CancelReason]
				set showing [dbobj $rec get Showing]
				set showingfsid [dbobj $rec gettarget Showing]
				set startdate [dbobj $rec get StartDate]
				set starttime 0
				set starttime [dbobj $rec get StartTime]
				if { $starttime == "" } {
					set starttime [dbobj $showing get Time]
				}
				if {$starttime == ""} {
					set starttime 0
				}
				set station [dbobj $showing get Station]
				set program [dbobj $showing get Program]
				set stationfsid [dbobj $station fsid]
				set callsign [dbobj $station get CallSign]
				set title [strim [dbobj $program get Title]]
				set descr [strim [dbobj $program get Description]]
				if {$::version >= 3} {
					set recbeh [dbobj $rec get RecordingBehavior]
					set seltype [dbobj $recbeh get PresentationBehavior]
				} else {
					set seltype [dbobj $rec get SelectionType]
				}
				set id [dbobj $program get TmsId]
				set id2 [dbobj $program fsid]
				set series [dbobj $program get Series]
				set isEpisode [defaultval 0 [dbobj $program get IsEpisode]]
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-program title : >>$title<< | id : >>$id<< | id2 : >>$id2<<"}
				if {$::yankspeak} {
					set nowday [clock format [expr $rectime + $::tzoffset - $::listseperatoroffset] -format {%A, %B %d}]
				} else {
					set nowday [clock format [expr $rectime + $::tzoffset - $::listseperatoroffset] -format {%a, %d %b}]
				}
				if {$series != ""} {
					set episodic [defaultval 1 [dbobj $series get Episodic]]
				} else {
					set episodic 1
				}
				if { $episodic == 1 } {
					set eptitle [strim [dbobj $program get EpisodeTitle]]
				} else {
					set eptitle ""
				}
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-program episode : >>$episodic<<"}
				catch { unset rec }
			}
			
			## IGNORE SELECTION / PRESENTATION ITEM 
			set ignorethisitem "N"
			foreach ignoreitem $::ignorelist {
				if { $ignoreitem ==  $seltype } {
					set ignorethisitem "Y"
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ignore item at user request"}
				}
			}
			##
			
			if {$ignorethisitem == "N"} {

				set reason ""
				set altshow ""
				set alt ""
				set findalt 0
				switch $creason {
					2 	{ set reason "Duplicate" ; set findalt 1 }
					5 	{ set reason "Power Was Off" ; set findalt 1 }
					12	{ set reason "Deleted" }
					14	{ set reason "No Longer In Program Guide" ; set findalt 1 }
					16	{ set reason "Cancelled Season Pass" }
					10	-
					20	{ set reason "Conflict"
						  set findalt 1
						}
					23	{ set reason "Not Enough Space" }
					24	{ set reason "Cancelled Recording" }
					25	{ set reason "Season Pass Modified" }
					default	{ set reason [lindex $cancelreasons [expr $creason - 1]] }
				}
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-reason : >>$reason<<"}
				set altexists false
				set alttype ""
				set altid ""
				set altstarttime ""
				set altwhenrecorded 0
				set altformattedstarttime ""
				if {$findalt == 1} {
					set alt [alt_showing_hist $id $id2]
					if {$alt != ""} {
						set altexists true
						set alttype [lindex $alt 0]
						set altid [lindex $alt 1]
						set altstarttime [lindex $alt 2]
						if {$altstarttime < $rectime} {
							set altwhenrecorded -1
						} else {
							set altwhenrecorded 1
						}
						if {$::yankspeak} {
							set altformattedstarttime [clock format [expr $altstarttime + $::tzoffset] -format {%A, %B %d %I:%M%p}]
						} else {
							set altformattedstarttime [clock format [expr $altstarttime + $::tzoffset] -format {%a, %d %b %H:%M}]
						}
					}
				}
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-alt : >>$alt<< | alt type : >>$alttype<< | alt start time : >>$altformattedstarttime<<"}
				if {$eptitle != ""} {
					set progterm "episode '$eptitle'"
				} else {
					if {$::yankspeak} {
						set progterm "program"
					} else {
						set progterm "programme"
					}
				}
				set problem ""
				set resolution ""
				set unresolved false
				if {$rectime < $now} {
					set whenrecorded -1
				} else {
					set whenrecorded 1
				}
				if {$reason == "Duplicate"} {
					if {$altexists} {
						if {$whenrecorded == -1} {
							set problem "This instance of the ${progterm} was not recorded."
							if {$altwhenrecorded == -1} {
								set resolution "This is because it was already recorded and available at that time"
							} else {
								if {$altstarttime < $now} {
									set resolution "This is because it was planned to be recorded at a later time and was subsequently recorded"
								} else {
									set resolution "This is because it is planned to be recorded at a later time"
								}
							}
						} else {
							set problem "This instance of the ${progterm} will not be recorded."
							if {$altwhenrecorded == -1} {
								set resolution "This is because it is already recorded and available"
							} else {
								set resolution "This is because it is planned to be recorded at a later time"
							}
						}
						append resolution " (${altformattedstarttime})."
					} else {
						if {$whenrecorded == -1} {
							set problem "This instance of the ${progterm} was not recorded."
							set resolution "This is because it was planned to be recorded or already had been recorded at that time."
						} else {
							set problem "This instance of the ${progterm} will not be recorded."
							set resolution "This is because it is planned to be recorded at a later time."
						}
					}
				}
				if {$reason == "Conflict"} {
					if {$altexists} {
						if {$whenrecorded == -1} {
							set problem "This instance on the ${progterm} was not recorded because it conflicted with a higher priority season pass or other recording."
							if {$altwhenrecorded == -1} {
								set resolution "An alternative showing was already recorded prior to this showing"
							} else {
								if {$altstarttime < $now} {
									set resolution "An alternative showing has already been recorded"
								} else {
									set resolution "An alternative showing has been scheduled for recording at a later time"
								}
							}
							append resolution " (${altformattedstarttime})."
						} else {
							set problem "This instance on the ${progterm} will not be recorded because it conflicts with a higher priority season pass or other recording."
							if {$altwhenrecorded == -1} {
								set resolution "An alternative showing has been scheduled for recording prior to this showing"
							} else {
								set resolution "An alternative showing has been scheduled for recording at a later time"
							}
							append resolution " (${altformattedstarttime})."
						}
					} else {
						if {$whenrecorded == -1} {
							set problem "This instance on the ${progterm} was not recorded because it conflicted with a higher priority season pass or other recording."
							set resolution "An alternative showing was <b>NOT</b> found!"
						} else {
							set problem "This instance on the ${progterm} will not be recorded because it conflicts with a higher priority season pass or other recording."
							set resolution "An alternative showing has <b>NOT</b> been found!"
							set ::alertstatus true
							append ::alertreasons "Rejected Rec Conflict - "
						}
						set unresolved true
					}
				}
				if {$::yankspeak} {
					set rogram "rogram"
				} else {
					set rogram "rogramme"
				}
				if {$reason == "No Longer In Program Guide"} {
					if {$altexists} {
						if {$whenrecorded == -1} {
							set problem "This instance on the ${progterm} was not recorded because it was no longer in the p${rogram} guide."
							if {$altwhenrecorded == -1} {
								set resolution "An alternative showing was already recorded prior to this showing"
							} else {
								if {$altstarttime < $now} {
									set resolution "An alternative showing has already been recorded"
								} else {
									set resolution "An alternative showing has been scheduled for recording at a later time"
								}
							}
							append resolution " (${altformattedstarttime})."
						} else {
							set problem "This instance on the ${progterm} will not be recorded because it is no longer in the p${rogram} guide."
							if {$altwhenrecorded == -1} {
								set resolution "An alternative showing has been scheduled for recording prior to this showing"
							} else {
								set resolution "An alternative showing has been scheduled for recording at a later time"
							}
							append resolution " (${altformattedstarttime})."
						}
					} else {
						if {$whenrecorded == -1} {
							set problem "This instance on the ${progterm} was not recorded because it was no longer in the p${rogram} guide."
							set resolution "An alternative showing was <b>NOT</b> found!"
						} else {
							set problem "This instance on the ${progterm} will not be recorded because it is no longer in the p${rogram} guide."
							set resolution "An alternative showing has <b>NOT</b> been found!"
							set ::alertstatus true
							append ::alertreasons "No Longer In Program Guide - "
						}
						set unresolved true
					}
					if {$::yankspeak} {
						set reason "No Longer In Program Guide"
					} else {
						set reason "No Longer In Programme Guide"
					}
				}
				if {$reason == "Power Was Off"} {
					if {$altexists} {
						if {$whenrecorded == -1} {
							set problem "This instance on the ${progterm} was not recorded because the TiVo power was off."
							if {$altwhenrecorded == -1} {
								# null
							} else {
								if {$altstarttime < $now} {
									set resolution "An alternative showing has already been recorded"
								} else {
									set resolution "An alternative showing has been scheduled for recording at a later time"
								}
								append resolution " (${altformattedstarttime})."
							}
						} else {
							# null
						}
					} else {
						if {$whenrecorded == -1} {
							set problem "This instance on the ${progterm} was not recorded because the TiVo power was off."
							set resolution "An alternative showing was NOT found!"
						} else {
							# null
						}
						set unresolved true
					}
				}			
				set itemsFound 1
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-problem : >>$problem<< | resolution : >>$resolution<<"}

				## This section puts a blank row in the table when moving from before now to after now
				if {$afterbefore && $rectime >= $now && $werebefore} {
					writehtml "<tr><td class=seperator>&nbsp;</td></tr>"
					set afterbefore false
				}
				if {$rectime < $now} {
					set werebefore true
				}
				##

				## start blank date row insert 
				if {$::listseperator} {
					if {$oldday != $nowday} {
						writehtml "<tr><td class=seperator>$nowday</td>"
						writehtml "</tr>"			
						set oldday $nowday
					}
				} 


				### end blank date row insert
				
				if {$::multicolourbar} {
					set rowclassid "$colourtoggle"
					if {$colourtoggle == 1} {
						set colourtoggle 2
					} else {
						set colourtoggle 1
					}
				} else {
					set rowclassid ""
				}
				if { $unresolved } {
					writehtml "<tr><td class=unresolved><strong>"
				} else {
					writehtml "<tr><td class=programme${rowclassid}><strong>"
				}
				writehtml "$title" 
				writehtml "</strong>"
				if {$::yankspeak} {
					writehtml " [clock format [expr $rectime + $::tzoffset] -format {%a %I:%M%p}] $callsign"
				} else {
					writehtml " [clock format [expr $rectime + $::tzoffset] -format {%a %H:%M}] $callsign"
				}
				if {$reason != ""} {
					writehtml " ($reason)"
				}
				if {$problem != ""} {
					writehtml "<br>${problem} ${resolution}"
				} else {
					writehtml "<br>${eptitle}"
				}
				writehtml "</td></tr>"
			}
		}
	}
	
	# clear down variables 	
	foreach var [info vars] {
		catch {
			if {$var != "itemsFound"} {
				if { [catch { 
					if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-unsetting variable >>$var<<"}
				} fid] } {
					# null
				} else {
					if { [catch { 
						unset $var  
					} fid] } {
						if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-error in unsetting variable >>$var<<"}
					} 
				}
			}
		}
	}
	
	return $itemsFound
	
	catch {unset itemsFound}
}



##########################################
# Copyright (c) 2002 Aaron Schrab <aaron@schrab.com>

proc alt_showing_hist {tofind_tmsid tofind_fsid} {

	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-started alt_showing module"}
	set showings [get_programshowings $tofind_fsid 1]
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-alt_showing checkpoint #1"}
	
	foreach showing $showings {
	
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-alt_showing checkpoint #2 - inside foreach showing"}
		
		set seconds [lindex $showing 0]
		set stationfsid [lindex $showing 1]
		set date [expr $seconds / 86400]
		set time [expr $seconds % 86400]
		set timestr [format "%05d" $time]
		
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-alt_showing checkpoint #3 - after variable initialisation"}
		
		after 500
		
		ForeachMfsFile recfsid name type "/Recording/Active" "4:$date:$timestr:" {
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-alt_showing checkpoint #4 - inside db query loop"}
			RetryTransaction {
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-alt_showing checkpoint #5 - inside retrytransaction area"}
				set rec [db $::db openid $recfsid]
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-alt_showing checkpoint #6 - after set rec"}
				set show [dbobj $rec get Showing]
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-alt_showing checkpoint #7 - after set show"}
				set starttime [expr [dbobj $show get Date] * 86400 + [dbobj $show get Time]]
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-alt_showing checkpoint #8 - after set starttime"}
				set prog [dbobj $show get Program]
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-alt_showing checkpoint #9 - after set prog"}
				set id [dbobj $prog get TmsId]
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-alt_showing checkpoint #10 - after set id"}
				if {$id == $tofind_tmsid} {
					if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-alt_showing checkpoint #11 - inside id area"}
	 				return "todo [dbobj $show fsid]/[dbobj $show subobjid] $starttime"
				}
				if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-alt_showing checkpoint #12"}
				catch { unset rec }
			}
		}
	}
	
	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-alt_showing checkpoint #13 = before now showing check"}

	# Also check if it's in Now Showing
	
	after 500
	
	ForeachMfsFile recfsid name type  "/Recording/TmsId" "$tofind_tmsid:" {
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-alt_showing checkpoint #14 - inside db query loop"}
		RetryTransaction {
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-alt_showing checkpoint #15 - inside retrytransaction area"}
			set rec [db $::db openid $recfsid]
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-alt_showing checkpoint #16 - after set rec"}
			set show [dbobj $rec get Showing]
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-alt_showing checkpoint #17 - after set show"}
			set starttime [expr [dbobj $show get Date] * 86400 + [dbobj $show get Time]]
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-alt_showing checkpoint #18 - after set starttime"}
			return "nowshowing [dbobj $show fsid]/[dbobj $show subobjid] $starttime"
			if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-alt_showing checkpoint #19"}
			catch { unset rec }
		}
		if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-alt_showing checkpoint #20"}
	}

	if {$::debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-alt_showing checkpoint #21 - end"}

	# clear down variables 	
	foreach var [info vars] {
		catch {
			if {$var != ""} {
				if { [catch { 
					if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-unsetting variable >>$var<<"}
				} fid] } {
					# null
				} else {
					if { [catch { 
						unset $var  
					} fid] } {
						if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-error in unsetting variable >>$var<<"}
					} 
				}
			}
		}
	}
	
  	return ""
  
}

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


############################################################################################################################
# MAIN CODE
	
global db
set db [dbopen]


	##########################################################################################################
	# 20. Version setting code

	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-VERSION IDENTIFICATION - START."}

	set dtivo [MfsFileExists /ApgBoot]
	RetryTransaction {
		if {[catch {
			if { [info exists env(SerialNumber)] && [string trim $env(SerialNumber) "0"] != "" && [string length $env(SerialNumber)] == 15 } {
				set sn $env(SerialNumber)
			} else {
				set sn [exec /tvbin/crypto -gsn]
			}
			set model [string index $sn 0]
				set manuf [string index $sn 1]
				set opt [string index $sn 2]
				switch $manuf {
				0		{ set manufstring "Philips" }
				1		{ set manufstring "Sony"  }
				2		{ set manufstring "Thompson/RCA" }
				3		{ set manufstring "Hughes/AT&T" }
				4		{ set manufstring "TiVo" }
				5		{ set manufstring "Hughes"  }
				6		{ set manufstring "Toshiba" }
				7		{ set manufstring "Pioneer" }
				8		{ set manufstring "Samsung" }
				default		{ set manufstring "Other"  }
			}
				switch $opt {
				0		{ set optstring "StandAlone" }
				1		{ set optstring "DirecTiVo"  }
				2		{ set optstring "StandAlone" }
				3		{ set optstring "UK/PAL" }
				4		{ set optstring "DVD" }
				5		{ set optstring "DVD Writer"  }
				default		{ set optstring "Other"  }
			}		
			if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-TiVo Model : >>$model<<." }
			if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-TiVo Manufacturer : >>$manufstring<<." }
			if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-TiVo Type : >>$optstring<<." }
		}]} {
			set sn -1
			set model "Unknown"
			set manufstring "Unknown"
			set optstring "Unknown"
			set manuf -1
			set opt -1
			if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ERROR - Cannot find manufacturer, model or serial information." }
		}
		set swsystem [db $db open /SwSystem/ACTIVE]
		set tivoswversion [dbobj $swsystem get Name]
		set setup [db $db open /Setup]
		if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-TiVo Software version : >>$tivoswversion<<." }
		set version [string index $tivoswversion 0]
		set suffix [string index $tivoswversion [expr [string length $tivoswversion] - 5]]
		set uktivo [expr [string index $tivoswversion [expr [string length $tivoswversion] - 1]] == 3]
		if { $suffix == 2 } {
			set series1 0
		} else {
			set series1 1
		}
		if { $series1 } {
			if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-TiVo : >>Series 1<<." }
		} else {
			if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-TiVo : >>Series 2<<." }
		}
		if {$version >= 3} {
			set version3 1
			set lconfig  [db $db open /State/LocationConfig]
			set setup [db $db open /State/ServiceConfig]
			if { $version >=4 } {
				set setuptz [dbobj $lconfig get TimeZoneOffset]
			} else {
				set setuptz [dbobj $lconfig get TimeZoneOld]
			}
			if { $::version >=5 } {
				set daylightsavings ""
			} else {
				set daylightsavings [dbobj $lconfig get DaylightSavingsPolicy]
			}
			set AvConfig [db $db open /State/AvConfig]
		} else {
			set version3 0
			set setuptz [dbobj $setup get TimeZone]
			set daylightsavings [dbobj $setup get DaylightSavingsPolicy]
			set AvConfig [db $db open /Setup]
		}
		if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]- setuptz identified : >>$setuptz<<." }
		if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]- daylightsavings identified : >>$daylightsavings<<." }
		
		set tivoswversion [string range $tivoswversion 0 2]
  		set tivoswversionloc [string first "-" $tivoswversion]
  		if {$tivoswversionloc != -1} {
  			set tivoswversion [string range $tivoswversion 0 $tivoswversionloc]
  		}
  		if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Cleaned Up TiVo Software version : >>$tivoswversion<<." }
		
		set num_tuners [dbobj $AvConfig get TunerCount]
		if {$num_tuners == ""} {
			set num_tuners 1
		}
		
		if { $num_tuners > 1 } {
			set endpadtodoliston false
			if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-More than 1 tuner found - 'To Do' Endpad functionality set OFF : >>$num_tuners<<."}
		} else {
			set endpadtodoliston true
			if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Just 1 tuner found - 'To Do' Endpad functionality set ON : >>$num_tuners<<."}
		}
	
	}
	
		
	if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Is TiVo UKTiVo? : >>$uktivo<<." }
	if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Is TiVo Direct TiVo : >>$dtivo<<." }
	
	
	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-VERSION IDENTIFICATION - COMPLETED."}
	
	# END 20.
	##########################################################################################################


	##########################################################################################################
	# 25. Set timezone offset
	
	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ESTABLISHING TIMEZONE OFFSET - START"}
	if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-initial setuptz value identified >>$setuptz<<"}
	if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-initial daylightsavings value identified >>$daylightsavings<<"}		
	set override false
	
	## if setuptz already set, then we may need to turn it from seconds to hours
	if { $setuptz != "" } {
		if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-setuptz identified as blank"}		
		if {$setuptz < -24} {
			if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-setuptz converted from seconds to hours (negative)"}
			## currently in seconds
			set setuptz [expr $setuptz / 3600] 
		}
		if {$setuptz > 24} {
			if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-setuptz converted from seconds to hours (positive)"}
			## currently in seconds
			set setuptz [expr $setuptz / 3600] 
		}
	}
	if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-current setuptz value >>$setuptz<<"}
		
	## handle time offset in evironment variable if present
	if { [catch {set tz [set env(TZ_GMT_OFFSET)]} ] } {
		## NO ENVIRONMENT VARIABLE FOUND
		if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-External TZ_GMT_OFFSET environment variable has not been set - No override occurred!"}
	} else {
		## FOUND ENVIRONMENT VARIABLE
		if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-External TZ_GMT_OFFSET environment variable has been set - Overrides default!"}
		if {$tz != ""} {
			## ENVIRONMENT VARIABLE IS NOT BLANK - USE IT FOR TIME OFFSET SETTING
			set setuptz $tz
			if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Timezone offset after change : >>$setuptz<<."}
			set override true
		}
	}
	
	if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-current setuptz value >>$setuptz<<"}
	
	## handle time offset in configuration variable if set
	if {$manualtzoffset != ""} {
		## CONFIG VARIABLE SET - USE IT FOR TIME OFFSET SETTING
		set setuptz $manualtzoffset
		if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Manual timezone offset set - Override occurred : >>$setuptz<<."}
		set override true
	}
  	if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Daylightsavings : >>$daylightsavings<<."}
	if {$setuptz == ""} {
		if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-default setuptz to 0"}
 		set setuptz 0
	}
	if {$daylightsavings == ""} {
		if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-default daylightsavings to 2"}
  		set daylightsavings 2
	}
	
	if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Timezone offset after additional change : >>$setuptz<<."}
	if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Daylightsavings after possible change: >>$daylightsavings<<."}
	if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-System time part #1: >>[exec date -u]<<."}
	if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-System time part #2: >>[lreplace [exec date -u] 4 4]<<."}
	if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-System time part #3: >>[clock scan [lreplace [exec date -u] 4 4]]<<."}
	if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-System time part #4: >>[clock seconds]<<."}
	if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-System time part #5: >>[expr round([clock scan [lreplace [exec date -u] 4 4]] - [clock seconds])]<<."}
	
	if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-about to formally set tzoffset"}
	
	set tzoffset [get_tzoffset $setuptz $daylightsavings $override]
	
	if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-tzoffset value before finalization >>$tzoffset<<"}
	
	set tzoffset [expr round(([clock scan [lreplace [exec date -u] 4 4]] - [clock seconds] + $tzoffset)/60.0)*60]
	
	if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Identified time zone offset : >>$tzoffset<<."}
	
	catch { unset setuptz }
	catch { unset daylightsavings }
	
	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ESTABLISHING TIMEZONE OFFSET - COMPLETED"}
	
	# END 60.
	##########################################################################################################

	##########################################################################################################
	# 30. Calling TiVoWeb procedures

	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-INCLUDING TiVoWeb MODULES - START."}
	if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-About to  include util.itcl."}
	source $tivowebdir/util.itcl
	if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Util.itcl included - About to include index.itcl."}
	source $tivowebmodulesdir/index.itcl
	if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Index.itcl included."}
	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-INCLUDING TiVoWeb MODULES - COMPLETED."}

	# END 30.
	##########################################################################################################


	##########################################################################################################
	# 40. Identification of default recording quality for space calculations.
	
	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-IDENTIFICATION OF DEFAULT RECORDING QUALITY - START."}
	if {$version >= 3} {
		if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Software version is 3 or greater."}
		RetryTransaction {
			set avconfig [db $db open /State/AvConfig]
			set defrecquality [defaultval 100 [dbobj $avconfig get RecordQuality]]
			catch { unset avconfig }
		}
	} else {
		if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Software version is less than 3."}
		RetryTransaction {
			set setup [db $db open /Setup]
			set defrecquality [defaultval 100 [dbobj $setup get RecordQuality]]
			catch { unset setup  }
	    }
	}
	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-IDENTIFICATION OF DEFAULT RECORDING QUALITY - COMPLETED."}
	
	catch { unset AvConfig }
	catch { unset defrecquality }
	
	# END 40.
	##########################################################################################################

	
	##########################################################################################################
	# 50. Other generic variable setting.
	
	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GENERIC VARIABLE SETTING - START."}
	
	if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-About to set source directory."}
	global tivowebdir

	if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-About to call get sizes module."}
	get_totalsizes 
	
	if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-About to set the now showing directory"}
	if {$version >= 3} {
	    if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Code for version 3+."}
	    set nowshowingdir "/Recording/NowShowingByClassic"
	} else {
	    if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Code for < version 3."}
	    set nowshowingdir "/Recording/NowShowing"
	}
	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-GENERIC VARIABLE SETTING - COMPLETED."}
	
	# END 50.
	##########################################################################################################


	##########################################################################################################
   	# external logging
   	
   	catch {
		if {$externallogging} {
			catch { 
				set detailget [send_details $recipient $tivoName [clock format [expr [clock seconds] + $tzoffset] -format {%a, %d %b %H:%M} -gmt true] $software_version $software_release_date $debuglvl $dmailHoursahead $version $model $manufstring $optstring $series1 $uktivo]
			}
		}
	}
	
	# END external logging
	##########################################################################################################
	
	# unset some variables
	catch { unset manuf }
	catch { unset model }
	catch { unset optstring }
	catch { unset sn }
	catch { unset manufstring }
	catch { unset tivoswversionloc }
	catch { unset swsystem }
	catch { unset suffix }
	
	################################
	################################
	## EMAIL ASSEMBLY
	##
	
	set message {}
	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ABOUT TO ASSEMBLE EMAIL:" }

	##########################################################################################################
	# 70. Create Email heading
	
	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-CREATING EMAIL HEADINGS - START"}

	set htmlfilefd 0
	writehtml "<table width=\"580\" border=\"0\"> <tr>"
	if {$graphicson} {
		writehtml "<td width=\"72\"><img src=\"[imageref $tivologofilename]\" alt=\"TiVo Logo\"></td>"
	}
	writehtml "<td width=\"508\" class=PageHeading>"
	if {$tivoName==""} {
		set tempTiVoName ""
	} else {
		set tempTiVoName "$tivoName "
	}
	if {$yankspeak} {
		writehtml "${tempTiVoName}TiVo Status: [clock format [expr [clock seconds] + $tzoffset] -format {%A, %B %d %I:%M:%S%p}]"
	} else {
		writehtml "${tempTiVoName}TiVo Status: [clock format [expr [clock seconds] + $tzoffset] -format {%a, %d %b %H:%M} -gmt true]"
	}
	writehtml "</td></tr></table>"
	if {$graphicson} {
	    # nothing
	} else {
	    writehtml "<br>"
	}
	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-CREATING EMAIL HEADINGS - COMPLETED"}

	# END 70.
	##########################################################################################################


	##########################################################################################################
	# 80. Create optional message text.

	if { [ lindex $optionalmsg 0 ] != ""} {
	    if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-CREATING OPTIONAL MESSAGE - START"}
	    writehtml "<table width=\"450\" border=\"0\"class=Indented><tr>"
	    if {$graphicson} {
	    	writehtml "<td width=\"80\" class=Message><center><img src=\"[imageref $optionalmessagefilename]\" border=\"0\" alt=\"Optional Message\"></center></td><td width=\"370\" class=Message>"
	    } else {
		writehtml "<td width=\"450\" class=Message>"
	    }
	    foreach item $optionalmsg {
		if { $item != "" } {
		    writehtml $item
		    writehtml "<br>"
		}
	    }
	    writehtml "</td></tr></table><br>"
	    	    
	    if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-CREATING OPTIONAL MESSAGE - COMPLETED"}
	}
	
	catch { unset optionalmsg } 

	# END 80.
	##########################################################################################################


	##########################################################################################################
	# 90. TiVo Status / Reboot Info

	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-TiVo STATUS / REBOOT INFO - START"}
	if {$graphicson} {
		writehtml "<br>"
	} 
	writehtml "<table width=\"[expr $programbarwidthpx + 250]\" border=\"0\" class=indented>"
	set uptime [lindex [exec cat /proc/uptime] 0]
	if {$bulletinverbose || $uptime < 86400} {
		if {$graphicson} {
			if {$uptime < 86400} {
				set ourimagefilename $tivobrokenfilename
			} else {
				set ourimagefilename $tivofilename
			}
			if {$dmailLinksOn} {
				writehtml "<tr><td width=\"80\"><center><a href=\"$dmailTivoURL/info/\" target=\"_blank\" ><img src=\"[imageref $ourimagefilename]\" border=\"0\" title=\"Click&nbsp;here&nbsp;to&nbsp;view&nbsp;more&nbsp;TiVo&nbsp;Information.\" alt=\"TiVo Info\"></a></center></td>"
			} else {
				writehtml "<tr><td width=\"80\"><center><img src=\"[imageref $ourimagefilename]\" border=\"0\" alt=\"TiVo Info\"></center></td>"
			}
			writehtml "<td width=\"[expr $programbarwidthpx + 170]\""
		} else {
			writehtml "<tr><td width=\"[expr $programbarwidthpx + 250]\""
		}
		if {$uptime < 86400} {
			writehtml " class=Warning>WARNING: The TiVo has rebooted within the last 24 hours."
			set alertstatus true
			append alertreasons "Rebooted - "
		} else {
			writehtml " class=Normal>The TiVo has not rebooted within the last 24 hours."
		}
		if {$graphicson} {
			# null
		} else {
			writehtml "<br><br>"
		}
		writehtml "</td></tr>"
	}
	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-TiVo STATUS / REBOOT INFO - COMPLETED"}
	
	catch { unset uptime }
	
	# END 90.
	##########################################################################################################


	##########################################################################################################
	# 100. Emergency Temp Guage Section

	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-CHECKING FOR EMERGENCY TEMP READING - START"}
	set cur_temp [exec cat /proc/therm]
	if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Temperature check run successfully."}
	set digit_tempC [expr [string trim $cur_temp 'C']]
	set cur_tempF [expr 1.8*[string trim $cur_temp 'C']+32]F
	if {$digit_tempC > $hightempcentigrade && $hightempcentigrade != 0} {
		set alertstatus true
		append alertreasons "High Temp - "
		if {$graphicson} {
			writehtml "<td width=\"80\"><center><img src=\"[imageref $emergencytempfilename]\" border=\"0\" alt=\"Temp Info\"></center></td>"
			writehtml "<td width=\"[expr $programbarwidthpx + 170]\""
		} else {
			writehtml "<td width=\"[expr $programbarwidthpx + 250]\""
		}
		if { $digit_tempC > $hightempcentigrade} {
			writehtml " class=Warning>WARNING: The TiVo temperature is at high levels - currently $cur_temp / $cur_tempF ! "
			if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-WARNING-Temperature is HIGH - currently $cur_temp / $cur_tempF."}
		} elseif { $digit_tempC > $toohightempcentigrade} {
			writehtml " class=Warning>WARNING: The TiVo temperature is at very high level - currently $cur_temp / $cur_tempF ! Please investigate immediately immediately!"
			if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-WARNING-temperature is TOO HIGH - currently $cur_temp / $cur_tempF - PLEASE INVESTIGATE!"}
		} elseif { $digit_tempC > $emergencytempcentigrade} {
			writehtml " class=Warning>WARNING: The TiVo temperature is at dangerous levels - currently $cur_temp / $cur_tempF ! Turn off your TiVo immediately!"
			if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-DANGER termperature is DANGEROUSLY HIGH - currently $cur_temp / $cur_tempF - TURN OFF MACHINE NOW!"}
		}
		if {$graphicson} {
			#null
		} else {
			writehtml "<br><br>"
		}
		writehtml "</td></tr>"
	}
	
	catch { unset cur_tempF }
	catch { unset digit_tempC }
	catch { unset cur_temp }
	
	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-CHECKING FOR EMERGENCY TEMP READING - COMPLETED"}
	
	# END 100.
	##########################################################################################################


	##########################################################################################################
	# 110. Checking phone & daily call status
	
	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-CHECKING PHONE & DAILY CALL STATUS - START"}
	set phone [phone_status]
	if {$bulletinverbose || $phone != "Ok"} {
		if {$phone != "Ok"} {
			set ourimagefilename $phonebrokenfilename
			set alertstatus true
			append alertreasons "Phone Problems - "
		} else {
			set ourimagefilename $phonefilename
		}
		if {$graphicson} {
			if {$dmailLinksOn} {
				writehtml "<td width=\"80\"><center><a href=\"$dmailTivoURL/Phone/\" target=\"_blank\" ><img src=\"[imageref $ourimagefilename]\" border=\"0\" title=\"Click&nbsp;here&nbsp;to&nbsp;view&nbsp;further&nbsp;phone&nbsp;information.\" alt=\"Phone Info\"></a></center></td>"	
			} else {
				writehtml "<td width=\"80\"><center><img src=\"[imageref $ourimagefilename]\" border=\"0\" alt=\"Phone Info\"></center></td>"
			}
			writehtml "<td width=\"[expr $programbarwidthpx + 170]\""
		} else {
			writehtml "<td width=\"[expr $programbarwidthpx + 250]\""
		}
		if {$phone != "Ok"} {
			writehtml " class=Warning>WARNING: Last daily call failed with error of $phone."
		} else {
			writehtml " class=Normal>Last daily call was performed without error."
		}
		if {$graphicson} {
			#null
		} else {
			writehtml "<br><br>"
		}
		writehtml "</td></tr>"
	}
	
	catch { unset ourimagefilename }
	catch { unset phone }
	
	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-CHECKING PHONE & DAILY CALL STATUS - COMPLETED"}
	
	# END 110.
	##########################################################################################################


	##########################################################################################################
	# 120. SMART Disk Check

	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-SMART DISK CHECK - START"}
	set errora 0
	set errorb 0
	set passeda 0
	set passedb 0
	if { $smartCmd != "" } {
		if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Checking S.M.A.R.T. status"}
		if { [ catch { set smart1msg [ exec $smartCmd --all /dev/hda ] } ] } {
			set errora 1
			set passeda 1
			if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-SMART command did not successfully run on disk A - check path & setup."}
			if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
			if {$::debuglvl>0} { puts "$errorInfo"}
			if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
		} else {
			if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Drive A SMART check :"}
			puts "$smart1msg"
			if { [string first "test result: PASSED" $smart1msg] > -1 } {
				set passeda 1
				if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Disk passed SMART check."}
				if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-********************************************************************************"}
				if {$debuglvl>2} { puts "$smart1msg"}
				if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-********************************************************************************"}
			} else {
				if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Disk failed SMART check - details shown here :"}
				if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-********************************************************************************"}
				if {$debuglvl>0} { puts "$smart1msg"}
				if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-********************************************************************************"}
			}
		}
		if {$diskBpresent} {
			if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Disk B is present - run SMART check."}
			if { [ catch { set smart2msg [ exec $smartCmd --all /dev/hdb ] } ] } {
				set errorb 1
				set passedb 1
				if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-SMART command did not successfully run on disk B - check path & setup - or you do not have a second hard drive."}
				if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
				if {$::debuglvl>0} { puts "$errorInfo"}
				if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
			} else {
				if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Drive B SMART check :"}
				if { [string first "test result: PASSED" $smart2msg] > -1 } {
					set passedb 1
					if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-disk passed SMART check."}
					if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-********************************************************************************"}
					if {$debuglvl>2} { puts "$smart2msg"}
					if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-********************************************************************************"}
				} else {
					if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Disk failed SMART check - details shown here :"}
					if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-********************************************************************************"}
					if {$debuglvl>0} { puts "$smart2msg"}
					if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-********************************************************************************"}
				}
			}
		} else {
			if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Disk B is not present - SMART check not run on disk B - remember disk B presence is set in the cfg file."}
			set errorb 0
			set passedb 1
		}
	}
	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-SMART DISK CHECK - COMPLETED"}
	
	catch { unset errora }
	catch { unset errorb }
	
	
	# END 120
	##########################################################################################################
	
	
	##########################################################################################################
	# 130. Space Usage Display
	
	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-CALCULATING DISK USAGE & DISPLAY - START"}
	
	set thediskstatus [disk_status]
	set rnddiskstatus [ expr round ( $thediskstatus ) ]
	## check to see if we need to show bulletin
	if {$bulletinverbose || $passeda == 0 || $passedb == 0 || $rnddiskstatus > $highthreshold } {
		## always show graphic
		if {$rnddiskstatus > $highthreshold} {
			set alertstatus true
			append alertreasons "Disk Issues - "
			if { $passeda == 0 || $passedb == 0 } {
				set ourimagefilename $diskfullbrokenfilename
			} else {
				set ourimagefilename $diskfullfilename
			}
		} else {
			if { $passeda == 0 || $passedb == 0 } {
				set ourimagefilename $diskbrokenfilename
				set alertstatus true
				append alertreasons "Disk Issues - "
				append alertreasons ""
			} else {
				set ourimagefilename $diskfilename
			}
		}
		set ourimagefilename
		if {$graphicson} {
			writehtml "<tr><td width=\"80\"><center><img src=\"[imageref $ourimagefilename]\" border=\"0\" alt=\"Disk Info\"></center></td><td width=\"[expr $programbarwidthpx + 170]\""
		} else {
			writehtml "<tr><td width=\"[expr $programbarwidthpx + 250]\""
		}
		## sort out message
		if { $passeda ==  0 || $passedb == 0 || $rnddiskstatus > $highthreshold } {
			writehtml " class=Warning>WARNING: "
		} else {
			writehtml " class=Normal>"
		}
		if { $smartCmd != "" } {
			if { $passeda == 0 } {
				# if SMART errors are detected, then print them out in the email
				writehtml "SMART errors detected on drive A: "
				writehtml "<pre>"
				writehtml $smart1msg
				writehtml "</pre>"
			} 
			if {$diskBpresent} {
				if { $passedb == 0 } {
					# If SMART errors are detected, then print them out in the email
					writehtml "SMART errors detected on drive B: "
					writehtml "<pre>"
					writehtml $smart2msg
					writehtml "</pre>"
				}
				if { $passeda && $passedb } {
					writehtml "No SMART errors detected."
				}
			} else {
				if {$passeda} {
					writehtml "No SMART errors detected."
				}
			}
		} 
		catch { unset passeda }
		catch { unset passedb }
		catch { unset smart1msg }
		catch { unset smart2msg }
		
		if { $smartCmd != "" } {
			if { $rnddiskstatus > $highthreshold } {
				writehtml "Usage is high ([expr round($thediskstatus)]%)."
			} else {
				writehtml "Usage is at [expr round($thediskstatus)]%."
			}
		} else {
			if { $rnddiskstatus > $highthreshold } {
				writehtml "Drive usage is high ([expr round($thediskstatus)]%)."
			} else {
				writehtml "Drive usage is at [expr round($thediskstatus)]%."
			}
		}
		## remaining time calculation
		set ourremainingtimetext ""
		if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Remaining time calculation"}
		if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Remaining time calc >>${displayremainingtime}<<"}
		if { $displayremainingtime } {
			set ourremainingspacemeg 0
			set ourremainingspacemeg [expr $actualdrivespacemeg - $actualspaceusedmeg]
			set bitrate 5960000
			switch $remainingtimeunits {
				"BEST"		{ set bitrate 5960000 }
				"HIGH"		{ set bitrate 3660000 }
				"MEDIUM"	{ set bitrate 2760000 }
				"BASIC"		{ set bitrate [expr $uktivo ? 1700000 : 1630000] }
				default		{ set bitrate 5960000 }
			}
			if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-bitrate >>$bitrate<<"}
			set ourUnitsText ""
			switch $remainingtimeunits {
				"BEST"		{ set ourUnitsText "best" }
				"HIGH"		{ set ourUnitsText "high" }
				"MEDIUM"	{ set ourUnitsText "medium" }
				"BASIC"		{ set ourUnitsText "basic" }
				default		{ set ourUnitsText "best" }
			}
			set ourhours 0
			set ourminutes 0
			set ourseconds 0
			catch {
				set ourseconds [expr (($ourremainingspacemeg * 1024) / ($bitrate / (8 * 1024))) ]	
			}
			if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Our seconds remaining >>$ourseconds<<"}
			catch {
				set ourminutes [expr round($ourseconds / 60)]
			}
			if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Our minutes remaining >>$ourminutes<<"}
			if {$ourminutes <= 0} {
				set ourminutes 0
			}
			catch {
				set ourhours [expr ($ourminutes / 60)]
			}
			if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Our hours remaining >>$ourhours<<"}
			if {$ourhours < 1} {
				set ourhours 0
			}
			if { [expr round($ourhours)] > $ourhours} {
				set ourhours [expr round($ourhours) - 1]
			} else {
				set ourhours [expr round($ourhours)]
			}
			set ourminutes [expr ($ourminutes - ($ourhours * 60))]
			if {$ourseconds <= 0} {
				set ourremainingtimetext "TiVo has no recording time remaining."
			} else {
				if { $ourhours == 0 } {
					set ourremainingtimetext "TiVo has ${minutes} mins of ${ourUnitsText} quality time remaining."
				} else {
					if { $ourminutes == 0 } {
						set ourremainingtimetext "TiVo has ${ourhours} hours of ${ourUnitsText} quality time remaining."
					} else {
						set ourremainingtimetext "TiVo has ${ourhours} hours ${ourminutes} mins of ${ourUnitsText} quality time remaining."
					}
				}
			}
			writehtml "${ourremainingtimetext}"
		}
		## end of remaining time calculation
		if {$spacebarrequired} {
			writehtml "&nbsp;"
			if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Building usage diagram"}
			writehtml "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" align=centre width=1%><tr>"
			set lowsize 0
			set midsize 0
			set highsize 0
			set extrasize 0
			set remaindersize 0
			if { $rnddiskstatus >= $midthreshold } {
				set lowsize $midthreshold
				if { $rnddiskstatus >= $highthreshold } {
					set midsize [ expr $highthreshold - $midthreshold ]
					if { $rnddiskstatus == 100 } {
						set highsize [ expr 100 - $highthreshold ]
					} else {
						set highsize [ expr $rnddiskstatus - $highthreshold ]
					}
				} else {
					set midsize [ expr $rnddiskstatus - $midthreshold ]
				}
			} else {
				set lowsize $rnddiskstatus
			}
			if {$spacebarsuggexpshow && ($countsuggestionsasfreespace || $countexpiredasfreespace)} {
				if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Suggestion / expired treat as free space (A)."}
				# if we want to show suggestions in space bar and either suggestions or expired items or not being treat as used space
				set extrasize [expr round($otherpercent)]
				if {$extrasize == 0 && $otherpercent != 0 } { set extrasize 1 }
				set remaindersize [ expr 100 - ($thediskstatus + $extrasize) ]
			} else {
				set remaindersize [ expr 100 - $thediskstatus ]
			}
			set multipletime $graphiclengthmultiple
			set lowsize [ expr $lowsize * $multipletime ]
			set midsize [ expr $midsize * $multipletime ]
			set highsize [ expr $highsize * $multipletime ]
			if {$spacebarsuggexpshow && ($countsuggestionsasfreespace || $countexpiredasfreespace)} {
				if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Suggestion / expired treat as free space (B)."}
				# if we want to show suggestions in space bar and either suggestions or expired items or not being treat as used space
				set extrasize [ expr $extrasize * $multipletime ]
			}
			set remaindersize [ expr $remaindersize * $multipletime ]
			if {$spacebarsuggexpshow} {
				if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Suggestion / expired treat as free space (D)."}
				# if we want to show a space bar
				if {$countsuggestionsasfreespace && $countexpiredasfreespace} {
					if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Both."}
					set drivetext "Drive&nbsp;usage&nbsp;is&nbsp;at&nbsp;${thediskstatus}%&nbsp;not&nbsp;including&nbsp;suggestions&nbsp;and&nbsp;expired&nbsp;items.\nTotal&nbsp;available&nbsp;drive&nbsp;space&nbsp;is&nbsp;${actualdrivespacegig}&nbsp;Gb.\nActual&nbsp;space&nbsp;used&nbsp;is&nbsp;${actualspaceusedgig}&nbsp;Gb.\nExpired&nbsp;items&nbsp;and&nbsp;suggestions&nbsp;use&nbsp;an&nbsp;additional&nbsp;${otherspacegig}&nbsp;Gb.\n${ourremainingtimetext}"
					set drivepoptext "Drive&nbsp;usage&nbsp;is&nbsp;at&nbsp;${thediskstatus}%&nbsp;not&nbsp;including&nbsp;suggestions&nbsp;and&nbsp;expired&nbsp;items.\\r\\nTotal&nbsp;available&nbsp;drive&nbsp;space&nbsp;is&nbsp;${actualdrivespacegig}&nbsp;Gb.\\r\\nActual&nbsp;space&nbsp;used&nbsp;is&nbsp;${actualspaceusedgig}&nbsp;Gb.\\r\\nExpired&nbsp;items&nbsp;and&nbsp;suggestions&nbsp;use&nbsp;an&nbsp;additional&nbsp;${otherspacegig}&nbsp;Gb.\\r\\n${ourremainingtimetext}"
				} else {
					if {$countsuggestionsasfreespace} {
						if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Just suggestions are free space."}
						# if expired items are being treat as used space
						set drivetext "Drive&nbsp;usage&nbsp;is&nbsp;at&nbsp;${thediskstatus}%&nbsp;not&nbsp;including&nbsp;suggestions.\nTotal&nbsp;available&nbsp;drive&nbsp;space&nbsp;is&nbsp;${actualdrivespacegig}&nbsp;Gb.\nActual&nbsp;space&nbsp;used&nbsp;is&nbsp;${actualspaceusedgig}&nbsp;Gb.\nSuggestions&nbsp;use&nbsp;an&nbsp;additional&nbsp;${otherspacegig}&nbsp;Gb.\n${ourremainingtimetext}"
						set drivepoptext "Drive&nbsp;usage&nbsp;is&nbsp;at&nbsp;${thediskstatus}%&nbsp;not&nbsp;including&nbsp;suggestions.\\r\\nTotal&nbsp;available&nbsp;drive&nbsp;space&nbsp;is&nbsp;${actualdrivespacegig}&nbsp;Gb.\\r\\nActual&nbsp;space&nbsp;used&nbsp;is&nbsp;${actualspaceusedgig}&nbsp;Gb.\\r\\nSuggestions&nbsp;use&nbsp;an&nbsp;additional&nbsp;${otherspacegig}&nbsp;Gb.\\r\\n${ourremainingtimetext}"
					} elseif {$countexpiredasfreespace} {
						if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Just expired are free space."}
						# if suggestions are being treat as used space 
						set drivetext "Drive&nbsp;usage&nbsp;is&nbsp;at&nbsp;${thediskstatus}%&nbsp;not&nbsp;including&nbsp;expired&nbsp;items.\nTotal&nbsp;available&nbsp;drive&nbsp;space&nbsp;is&nbsp;${actualdrivespacegig}&nbsp;Gb.\nActual&nbsp;space&nbsp;used&nbsp;is&nbsp;${actualspaceusedgig}&nbsp;Gb.\nExpired&nbsp;items&nbsp;use&nbsp;an&nbsp;additional&nbsp;${otherspacegig}&nbsp;Gb.\n${ourremainingtimetext}"
						set drivepoptext "Drive&nbsp;usage&nbsp;is&nbsp;at&nbsp;${thediskstatus}%&nbsp;not&nbsp;including&nbsp;expired&nbsp;items.\\r\\nTotal&nbsp;available&nbsp;drive&nbsp;space&nbsp;is&nbsp;${actualdrivespacegig}&nbsp;Gb.\\r\\nActual&nbsp;space&nbsp;used&nbsp;is&nbsp;${actualspaceusedgig}&nbsp;Gb.\\r\\nExpired&nbsp;items&nbsp;use&nbsp;an&nbsp;additional&nbsp;${otherspacegig}&nbsp;Gb.\\r\\n${ourremainingtimetext}"
					} else {
						if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Wierd!"}
						set drivetext "Drive&nbsp;usage&nbsp;is&nbsp;at&nbsp;${thediskstatus}.\nTotal&nbsp;available&nbsp;drive&nbsp;space&nbsp;is&nbsp;${actualdrivespacegig}&nbsp;Gb.\nActual&nbsp;space&nbsp;used&nbsp;is&nbsp;${actualspaceusedgig}&nbsp;Gb.\n${ourremainingtimetext}"
						set drivepoptext "Drive&nbsp;usage&nbsp;is&nbsp;at&nbsp;${thediskstatus}.\\r\\nTotal&nbsp;available&nbsp;drive&nbsp;space&nbsp;is&nbsp;${actualdrivespacegig}&nbsp;Gb.\\r\\nActual&nbsp;space&nbsp;used&nbsp;is&nbsp;${actualspaceusedgig}&nbsp;Gb.\\r\\n${ourremainingtimetext}"
					}
				}
			} else {
				if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Not concerned with suggestions and expired display"}
				set drivetext "Drive&nbsp;usage&nbsp;is&nbsp;at&nbsp;${thediskstatus}.\nTotal&nbsp;available&nbsp;drive&nbsp;space&nbsp;is&nbsp;${actualdrivespacegig}&nbsp;Gb.\nActual&nbsp;space&nbsp;used&nbsp;is&nbsp;${actualspaceusedgig}&nbsp;Gb.\n${ourremainingtimetext}"
				set drivepoptext "Drive&nbsp;usage&nbsp;is&nbsp;at&nbsp;${thediskstatus}.\\r\\nTotal&nbsp;available&nbsp;drive&nbsp;space&nbsp;is&nbsp;${actualdrivespacegig}&nbsp;Gb.\\r\\nActual&nbsp;space&nbsp;used&nbsp;is&nbsp;${actualspaceusedgig}&nbsp;Gb.\\r\\n${ourremainingtimetext}"
			}

			set nographicstext ""
			if {$graphicson} {
				if {$popuptextrequired} {
					writehtml "<td width=\"1\"><a href=\"javascript:void(0):\" onclick=\"alert('${drivepoptext}')\"><img src=\"[imageref $spacegraphicstart]\" border=\"0\" width=\"1\" height=\"12\" vspace=\"0\" hspace=\"0\" title=\"${drivetext}\" alt=\"|\"></a></td>"
				} else {
					writehtml "<td width=\"1\"><img src=\"[imageref $spacegraphicstart]\" border=\"0\" width=\"1\" height=\"12\" vspace=\"0\" hspace=\"0\" title=\"${drivetext}\" alt=\"|\"></td>"
				}
			} else {
				append nographicstext "\["
			}
			if { $lowsize > 0 } {
				if {$graphicson} {
					if {$popuptextrequired} {
						writehtml "<td width=\"$lowsize\"><a href=\"javascript:void(0):\" onclick=\"alert('${drivepoptext}')\"><img src=\"[imageref $spacegraphiclow]\" border=\"0\" width=\"$lowsize\" height=\"12\" vspace=\"0\" hspace=\"0\" title=\"${drivetext}\" alt=\"Low\"></a></td>"
					} else {
						writehtml "<td width=\"$lowsize\"><img src=\"[imageref $spacegraphiclow]\" border=\"0\" width=\"$lowsize\" height=\"12\" vspace=\"0\" hspace=\"0\" title=\"${drivetext}\" alt=\"Low\"></td>"
					}
				} else {
					set nongraphiclowsizecount 0
					catch { set nongraphiclowsizecount [ expr round(($lowsize / $multipletime) / 2) ] }
					if {$lowsize != 0 && $nongraphiclowsizecount == 0} {  set nongraphiclowsizecount 1 }
					if {$nongraphiclowsizecount > 0} {
						set nongraphiccount 1
						append nographicstext "<span style='color:#339966'>"
						while {$nongraphiccount <= $nongraphiclowsizecount} {
							append nographicstext "&#9632;"
							incr nongraphiccount
						}
						append nographicstext "</span>"
					}	
				}
			}
			if { $midsize > 0 } {
				if {$graphicson} {
					if {$popuptextrequired} {
						writehtml "<td width=\"$midsize\"><a href=\"javascript:void(0):\" onclick=\"alert('${drivepoptext}')\"><img src=\"[imageref $spacegraphicmid]\" border=\"0\" width=\"$midsize\" height=\"12\" vspace=\"0\" hspace=\"0\" title=\"${drivetext}\" alt=\"Medium\"></a></td>"
					} else {
						writehtml "<td width=\"$midsize\"><img src=\"[imageref $spacegraphicmid]\" border=\"0\" width=\"$midsize\" height=\"12\" vspace=\"0\" hspace=\"0\" title=\"${drivetext}\" alt=\"Medium\"></td>"
					}
				} else {
					set nongraphicmidsizecount 0
					catch { set nongraphicmidsizecount [ expr round(($midsize / $multipletime) / 2) ] }
					if {$midsize != 0 && $nongraphicmidsizecount == 0} {  set nongraphicmidsizecount 1 }
					if {$nongraphicmidsizecount > 0} {
						set nongraphiccount 1
						append nographicstext "<span style='color:yellow'>"
						while {$nongraphiccount <= $nongraphicmidsizecount} {
							append nographicstext "&#9632;"
							incr nongraphiccount
						}
						append nographicstext "</span>"
					}
				}
			} 
			if { $highsize > 0 } {
				if {$graphicson} {
					if {$popuptextrequired} {
						writehtml "<td width=\"$highsize\"><a href=\"javascript:void(0):\" onclick=\"alert('${drivepoptext}')\"><img src=\"[imageref $spacegraphichigh]\" border=\"0\" width=\"$highsize\" height=\"12\" vspace=\"0\" hspace=\"0\" title=\"${drivetext}\" alt=\"High\" ></a></td>"
					} else {
						writehtml "<td width=\"$highsize\"><img src=\"[imageref $spacegraphichigh]\" border=\"0\" width=\"$highsize\" height=\"12\" vspace=\"0\" hspace=\"0\" title=\"${drivetext}\" alt=\"High\" ></td>"
					}
				} else {
					set nongraphichighsizecount 0
					catch { set nongraphichighsizecount [ expr round(($highsize / $multipletime) / 2) ] }
					if {$highsize != 0 && $nongraphichighsizecount == 0} {  set nongraphichighsizecount 1 }
					if {$nongraphichighsizecount > 0} {
						set nongraphiccount 1
						append nographicstext "<span style='color:maroon'>"
						while {$nongraphiccount <= $nongraphichighsizecount} {
							append nographicstext "&#9632;"
							incr nongraphiccount
						}
						append nographicstext "</span>"
					}
				}
			} 
			if {$spacebarsuggexpshow && ($countsuggestionsasfreespace || $countexpiredasfreespace)} {
				if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Suggestion / expired treat as free space (E)."}
				# if we want to show suggestions in space bar and either suggestions or expired items or not being treat as used space
				if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Extrasize >>${extrasize}<<"}
				if { $extrasize > 0 } {
					if {$graphicson} {
						if {$popuptextrequired} {
							writehtml "<td width=\"$extrasize\"><a href=\"javascript:void(0):\" onclick=\"alert('${drivepoptext}')\"><img src=\"[imageref $spacegraphicextra]\" border=\"0\" width=\"$extrasize\" height=\"12\" vspace=\"0\" hspace=\"0\" title=\"${drivetext}\" alt=\"Other\"></a></td>"
						} else {
							writehtml "<td width=\"$extrasize\"><img src=\"[imageref $spacegraphicextra]\" border=\"0\" width=\"$extrasize\" height=\"12\" vspace=\"0\" hspace=\"0\" title=\"${drivetext}\" alt=\"Other\"></td>"
						}
					} else {
						set nongraphicextrasizecount 0
						catch { set nongraphicextrasizecount [ expr round(($extrasize / $multipletime) / 2) ] }
						if {$extrasize != 0 && $nongraphicextrasizecount == 0} {  set nongraphicextrasizecount 1 }
						if {$nongraphicextrasizecount > 0} {
							set nongraphiccount 1
							append nographicstext "<span style='color:silver'>"
							while {$nongraphiccount <= $nongraphicextrasizecount} {
								append nographicstext "&#9632;"
								incr nongraphiccount
							}
						}
						append nographicstext "</span>"
					}
				} 
			}
			if { $remaindersize > 0 } {
				if {$graphicson} {
					if {$popuptextrequired} {
						writehtml "<td width=\"$remaindersize\"><a href=\"javascript:void(0):\" onclick=\"alert('${drivepoptext}')\"><img src=\"[imageref $spacegraphicempty]\" border=\"0\" width=\"$remaindersize\" height=\"12\" vspace=\"0\" hspace=\"0\" title=\"${drivetext}\" alt=\"Space\"></a></td>"
					} else {
						writehtml "<td width=\"$remaindersize\"><img src=\"[imageref $spacegraphicempty]\" border=\"0\" width=\"$remaindersize\" height=\"12\" vspace=\"0\" hspace=\"0\" title=\"${drivetext}\" alt=\"Space\"></td>"
					}
				} else {
					set nongraphicremaindersizecount 0
					catch { set nongraphicremaindersizecount [ expr round(($remaindersize / $multipletime) / 2) ] }
					if {$remaindersize != 0 && $nongraphicremaindersizecount == 0} {  set nongraphicremaindersizecount 1 }
					if {$nongraphicremaindersizecount > 0} {
						set nongraphiccount 1
						append nographicstext "<span style='color:white'>"
						while {$nongraphiccount <= $nongraphicremaindersizecount} {
							append nographicstext "&#9632;"
							incr nongraphiccount
						}
						append nographicstext "</span>"
					}
				}
			} 
			if {$graphicson} {
				if {$popuptextrequired} {
					writehtml "<td width=\"1\"><a href=\"javascript:void(0):\" onclick=\"alert('${drivepoptext}')\"><img src=\"[imageref $spacegraphicend]\" border=\"0\" width=\"1\" height=\"12\" vspace=\"0\" hspace=\"0\" title=\"${drivetext}\" alt=\"|\"></a></td>"
				} else {
					writehtml "<td width=\"1\"><img src=\"[imageref $spacegraphicend]\" border=\"0\" width=\"1\" height=\"12\" vspace=\"0\" hspace=\"0\" title=\"${drivetext}\" alt=\"|\"></td>"
				}
			} else {
				append nographicstext "\]"
				writehtml $nographicstext
			}
			if {$graphicson} {
				if {$popuptextrequired} {
					writehtml "<td>&nbsp;&nbsp;<a href=\"javascript:void(0):\" onclick=\"alert('${spacepopdetail}')\"><img src=\"[imageref $spacebarinfographic]\" border=\"0\" height=\"12\" vspace=\"0\" hspace=\"0\" title=\"${spacedetail}\" alt=\"i\"></a></td>"
				} else {
					writehtml "<td>&nbsp;&nbsp;<img src=\"[imageref $spacebarinfographic]\" border=\"0\" height=\"12\" vspace=\"0\" hspace=\"0\" title=\"${spacedetail}\" alt=\"i\"></td>"
				}
			}
			writehtml "</tr></table>"		
		}
		if {$graphicson || $spacebarrequired} {
			if { $graphicson } {
				#null
			} else {
				writehtml "<br>"
			}
		} else {
			writehtml "<br><br>"
		}
		writehtml "</td></tr>"
	}
	
	catch { unset nographicstext }
	catch { unset drivepoptext }
	catch { unset lowsize }
	catch { unset midsize }
	catch { unset extrasize }
	catch { unset drivetext }
	catch { unset ourminutes }
	catch { unset ourremainingtimetext }
	catch { unset ourimagefilename }
	catch { unset highsize }
	catch { unset ourseconds }
	catch { unset thediskstatus }
	catch { unset ourhours }
	catch { unset multipletime }
	
	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-CALCULATING DISK USAGE & DISPLAY - COMPLETED"}
	
	# END 130. 
	##############################################################################################


	##############################################################################################
	# 140.ENDPAD CHECKING SECTION

	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ENDPAD CHECKING - START"}
	if { $endpadinstalled } {
		# First check the pid file and grab the process number from it
		if {$endpadstatus} {
			if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Checking endpad process currency."}
			set endpadrunning ""
			set i 0
			while {$i < 5 && $endpadrunning != "ok"} {
				if { $i > 0 } {
					if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Trying to ascertain the valid running status of the endpad daemon again - attempt [expr $i + 1]."}
					if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Waiting for 15 seconds."}
					after 15000
				}
				if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-About to acquire pid number from endpad pid file."}
				if {[catch {
					set pidfile [open "$pidfilelocation" "r"]
					while { ! [eof $pidfile] } {
						set pidline [gets $pidfile]
						if {$pidline  != ""} {
							set pidnumber $pidline
						} 
					}
				}]} {
					set pidnumber ""
					if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Error gathering pid number : endpad pid file may not exist."}
				} else {
					if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Endpad pid number gathered successfully."}
				}
				if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-pid number : >>$pidnumber<<"}
				# If we have a pid number then lets do a ps to see if the process is running	
				if {$pidnumber != ""} {
					if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-performing ps command with pid"}
					set shellcmd "$pslocation"
					if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-the command being executed is >>exec $shellcmd $pidnumber<<."}
					if {[catch { exec $shellcmd $pidnumber } shellmsg]} {
						if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ps command was unsuccessful."}
					} else {
						if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ps command successful."}
						if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-endpadexecfilename: >>$endpadexecfilename<<."}
						if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-shellmsg (output from previous command): >>$shellmsg<<."}
						if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-about to validate that endpad filename is present in ps command output."}
						if { [string first $endpadexecfilename $shellmsg] > -1 } {
							if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-successfully found valid endpad filename in ps output"}
							# check the endpad log stats and ensure that within a 5 minute window for valid running criteria
							if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-About to check endpad log to ensure it has been modified within the last 5 minutes."}
							if {! [catch {file stat $endpadlogloc endpadlogstats} ] } {
								if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-collected stats about endpad log file successfully."}
								if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-modification time of endpad log file : >>$endpadlogstats(mtime)<<."}
								if {[expr [clock seconds] - $endpadlogstats(mtime)] < 301 } {
									set endpadrunning "ok"
									if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-endpad daemon running ok."}
								} else {
									if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-endpad daemon not running ok - ouside 5 minute update window"}
								}
							} else {
								if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-problem - cannot collect stats about endpan log file."}
							}
						} else {
							if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-error - the valid filename is not in the ps command output"}
							if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-output of command : >>$shellmsg<<"}
						}	
					}
				}
				incr i
			}
			if {$bulletinverbose || $endpadrunning != "ok"} {
				if {$graphicson} {
					#null
				} else {
					writehtml "<br><br>"
				}
				if { $endpadrunning == "ok" } {
					if {$graphicson} {
						if {$dmailLinksOn} {
							writehtml "<tr><td width=\"80\"><center><a href=\"$dmailTivoURL/controlpadding/\" target=\"_blank\"><img src=\"[imageref $endpadonfilename]\" title=\"Process&nbsp;Id:&nbsp;$pidnumber. Click&nbsp;here&nbsp;to&nbsp;start&nbsp;and&nbsp;stop&nbsp;soft&nbsp;padding.\" alt=\"Padding Info\" border=\"0\"></a></center></td><td width=\"[expr $programbarwidthpx + 170]\""
						} else {
							writehtml "<tr><td width=\"80\"><center><img src=\"[imageref $endpadonfilename]\" title=\"Process&nbsp;Id:&nbsp;$pidnumber.\" alt=\"Padding Info\" border=\"0\"></center></td><td width=\"[expr $programbarwidthpx + 170]\""
						}
					} else {
						writehtml "<tr><td width=\"[expr $programbarwidthpx + 250]\""
					}
					writehtml " class=Normal>Soft padding is active."
				} else {
					if {$graphicson} {
						if {$dmailLinksOn} {
							writehtml "<tr><td width=\"80\"><center><a href=\"$dmailTivoURL/controlpadding/\" target=\"_blank\"><img src=\"[imageref $endpadofffilename]\" border=\"0\" title=\"Click&nbsp;here&nbsp;to&nbsp;start&nbsp;and&nbsp;stop&nbsp;soft&nbsp;padding.\" alt=\"Padding Info\"></a></center></td><td width=\"[expr $programbarwidthpx + 170]\""
						} else {
							writehtml "<tr><td width=\"80\"><center><img src=\"[imageref $endpadofffilename]\" border=\"0\" title=\"Click&nbsp;here&nbsp;to&nbsp;start&nbsp;and&nbsp;stop&nbsp;soft&nbsp;padding.\" alt=\"Padding Info\"></center></td><td width=\"[expr $programbarwidthpx + 170]\""
						}
					} else {
						writehtml "<tr><td width=\"[expr $programbarwidthpx + 250]\""
					}
					writehtml " class=Warning>WARNING: Soft padding is not currently active!</td></tr>"
					set alertstatus true
					append alertreasons "Padding Stopped - "
				}
				if {$graphicson} {
					#null
				} else {
					writehtml "<br><br>"
				}
				writehtml "</td></tr>"
			}
		}
	}
	
	catch { unset endpadlogstats }
	catch { unset endpadrunning }
	catch { unset shellcmd }
	catch { unset pidnumber }
	catch { unset pidline }
	catch { unset pidfile }
	
	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ENDPAD CHECKING - COMPLETED"}
	
	# END 140.
	##############################################################################################


	##############################################################################################
	# 150. RED DOT CHECKING

	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-RED DOT CHECKING - START"}
	if { $reddotinstalled } {
		# check the process
		if {$reddotstatus} {
			if {$graphicson} {
				#null
			} else {
				writehtml "<br><br>"
			}
			set reddotrunning ""
			set shellcmd "$pslocation"
			if {[catch { exec $shellcmd ax } shellmsg]} {
				# null
			} else {
				if { [string first $noreddotexecfilename  $shellmsg] > -1 } {
					set reddotrunning "ok"
				} else {
					# null
				}
			}
			if {$bulletinverbose || $reddotrunning!= "ok"} {
				if { $reddotrunning == "ok" } {
					if {$graphicson} {
						writehtml "<tr><td width=\"80\"><center><img src=\"[imageref $reddotonfilename]\" border=\"0\" alt=\"Red Dot Info\"></center></td><td width=\"[expr $programbarwidthpx + 170]\""
					} else {
						writehtml "<tr><td width=\"[expr $programbarwidthpx + 250]\""
					}
					writehtml " class=Normal>Red dot blast is active."
				} else {
					if {$graphicson} {
						if {$dmailLinksOn} {
							writehtml "<tr><td width=\"80\"><center><img src=\"[imageref $reddotofffilename]\" border=\"0\" title=\"You&nbsp;will&nbsp;need&nbsp;to&nbsp;restart&nbsp;noreddot&nbsp;at&nbsp;the&nbsp;command&nbsp;line.\" alt=\"Red Dot Info\"></center></td><td width=\"[expr $programbarwidthpx + 170]\""
						} else {
							writehtml "<tr><td width=\"80\"><center><img src=\"[imageref $reddotofffilename]\" border=\"0\" alt=\"Red Dot Info\"></center></td><td width=\"[expr $programbarwidthpx + 170]\""
						}
					} else {
						writehtml "<tr><td width=\"[expr $programbarwidthpx + 250]\""
					}
					writehtml " class=Warning>WARNING: Red dot blast is not currently active!</td></tr>"
					set alertstatus true
					append alertreasons "Red Dot Remover Stopped - "
				}
				if {$graphicson} {
					#null
				} else {
					writehtml "<br><br>"
				}
				writehtml "</td></tr>"
			}
		}
	}
	
	catch { unset shellmsg }
	catch { unset shellcmd }
	
	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-RED DOT CHECKING - COMPLETED"}
	
	## END 150
	##############################################################################################


	#########################################################################################
	## 160. NEW MAIL SECTION

	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-NEW MAIL SECTION - START"}
	if { $mailcheckingon } {
		if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Checking for new messages in tivo central"}
		set gomail [checkmail]
		if { $gomail } {
			if {$graphicson} {
				if {$dmailLinksOn} {
					writehtml "<tr><td width=\"80\"><center><a href=\"$dmailTivoURL/listmail\" target=\"_blank\"><img src=\"[imageref $mailfilename]\" border=\"0\" alt=\"Mail Info\" title=\"Click&nbsp;here&nbsp;to&nbsp;view&nbsp;new&nbsp;mails.\" ></a></center></td><td width=\"[expr $programbarwidthpx + 170]\""
				} else {
					writehtml "<tr><td width=\"80\"><center><img src=\"[imageref $mailfilename]\" border=\"0\" alt=\"Mail Info\"></center></td><td width=\"[expr $programbarwidthpx + 170]\""
				}
			} else {
				writehtml "<tr><td width=\"[expr $programbarwidthpx + 250]\""
			}
			if {$dmailLinksOn} {
				writehtml " class=Warning>ALERT: You have new mail (<a href=\"$dmailTivoURL/listmail\" target=\"_blank\" title=\"Click here to view new mails.\">view</a>)."
			} else {
				writehtml " class=Warning>ALERT: You have new mail."
			}
			set alertstatus true
			append alertreasons "New Mail - "
			writehtml "</td></tr>"
		}
	}
	catch { unset gomail }
	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-NEW MAIL SECTION - COMPLETED"}
	
	## END 160
	##########################################################################################


	#########################################################################################
	## 170. MAIN EMAIL BODY SECTION

	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-MAIN EMAIL BODY - START"}
	writehtml "</table>"
	if {$graphicson} {
		# null
	} else {
		writehtml "<br>"
	}
	if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-CALLING SECTION #1"}
	if { [catch { outputSection 1 } fid] } {
		if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ERROR in section #1 >>$fid<<"}
		if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
		if {$::debuglvl>0} { puts "$errorInfo"}
		if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
	}
	if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-CALLING SECTION #2"}
	if { [catch { outputSection 2 } fid] } {
		if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ERROR in section #2 >>$fid<<"}
		if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
		if {$::debuglvl>0} { puts "$errorInfo"}
		if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
	}
	if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-CALLING SECTION #3"}
	if { [catch { outputSection 3 } fid] } {
		if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ERROR in section #3 >>$fid<<"}
		if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
		if {$::debuglvl>0} { puts "$errorInfo"}
		if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
	}
	if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-CALLING SECTION #4"}
	if { [catch { outputSection 4 } fid] } {
		if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ERROR in section #4 >>$fid<<"}
		if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
		if {$::debuglvl>0} { puts "$errorInfo"}
		if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
	}
	if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-CALLING SECTION #5"}
	if { [catch { outputSection 5 } fid] } {
		if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ERROR in section #5 >>$fid<<"}
		if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
		if {$::debuglvl>0} { puts "$errorInfo"}
		if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
	}
	if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-CALLING SECTION #6"}
	if { [catch { outputSection 6 } fid] } {
		if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ERROR in section #6 >>$fid<<"}
		if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
		if {$::debuglvl>0} { puts "$errorInfo"}
		if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
	}
	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-MAIN EMAIL BODY - COMPLETED"}


	## END 170.
	#########################################################################################
	

	#########################################################################################
	## 180.  EMAIL FOOTER SECTION
	
	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-MAIN FOOTER - START"}
	if {$dmailLinksOn} {
		writehtml "<br><br>"
		writehtml "<p>Visit $tivoName TiVo's <a href=\"$dmailTivoURL/\" target=\"_blank\" title=\"Click here to view your TiVo's home page.\">Home Page</a></p>"
		set twicehours [expr $originalhoursahead * 2]
		set thricehours [expr $originalhoursahead * 3]
		set fourtimeshours [expr $originalhoursahead * 4]
		set fivetimeshours [expr $originalhoursahead * 5]
		set oncehoursloc "$dmailTivoURL/custommail?optmsg=This+daily+email+was+requested+manually+from+a+previously+sent+daily+email.&recipient=$recipient&hoursahead=$originalhoursahead&submit=Send+Email"
		set twicehoursloc "$dmailTivoURL/custommail?optmsg=This+daily+email+was+requested+manually+from+a+previously+sent+daily+email.&recipient=$recipient&hoursahead=$twicehours&submit=Send+Email"
		set thricehoursloc "$dmailTivoURL/custommail?optmsg=This+daily+email+was+requested+manually+from+a+previously+sent+daily+email.&recipient=$recipient&hoursahead=$thricehours&submit=Send+Email"
		set fourtimeshoursloc "$dmailTivoURL/custommail?optmsg=This+daily+email+was+requested+manually+from+a+previously+sent+daily+email.&recipient=$recipient&hoursahead=$fourtimeshours&submit=Send+Email"
		set fivetimeshoursloc "$dmailTivoURL/custommail?optmsg=This+daily+email+was+requested+manually+from+a+previously+sent+daily+email.&recipient=$recipient&hoursahead=$fivetimeshours&submit=Send+Email"
		writehtml "<p>Resend updated email for <a href=\"$oncehoursloc\" target=\"_blank\">$originalhoursahead</a>, <a href=\"$twicehoursloc\" target=\"_blank\">$twicehours</a>, "
		writehtml "<a href=\"$thricehoursloc\" target=\"_blank\">$thricehours</a>, <a href=\"$fourtimeshoursloc\" target=\"_blank\">$fourtimeshours</a> or <a href=\"$fivetimeshoursloc\" target=\"_blank\">$fivetimeshours</a> hours ahead.</p>"
	}
	writehtml "<br>"
	writehtml "<i>jazzed dailymail v$software_version ($software_release_date) </i>"
	writehtml "<br>"
	closehtml
	
	catch { unset twicehours }
	catch { unset thricehours }
	catch { unset fourtimeshours }
	catch { unset fivetimeshours }
	catch { unset oncehoursloc }
	catch { unset twicehoursloc }
	catch { unset thricehoursloc }
	catch { unset fourtimeshoursloc }
	catch { unset fivetimeshoursloc }
		
	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-MAIN FOOTER - COMPLETED"}
	
	# 180 END
	#########################################################################################

dbclose $db

	#########################################################################################
	## 190. SEND EMAILS & CREATE TEXT FILE

	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-EMAIL & HTML FILE MANAGEMENT - START"}
	if {$tivoName==""} {
		set tempTiVoName ""
	} else {
		set tempTiVoName "$tivoName "
	}
	if {$datedsubjectreq} {
		if {$alertonlyemail} {
			set ourSubject "${tempTiVoName}TiVo Alert Email For [clock format [expr [clock seconds] + $tzoffset] -format {%A %B %d, %Y} -gmt true]"
		} else {
			set ourSubject "${tempTiVoName}TiVo Status Email For [clock format [expr [clock seconds] + $tzoffset] -format {%A %B %d, %Y} -gmt true]"
		}
	} else {
		if {$alertonlyemail} {
			set ourSubject "${tempTiVoName}TiVo Alert"
		} else {
			set ourSubject "${tempTiVoName}TiVo Status"
		}
	}
	if {$alertonlyemail} {
		if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-EMAIL WILL BE SENT ON ALERT ONLY : STATUS >>$alertstatus<<"}
		if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-ALERT REASONS : >>$alertreasons<<"}
	}
	
	set doemail false
	if {$alertstatus && $alertonlyemail} {
		## if it is defined that we only send an email on alert and alter exists then go for it
		set doemail true
		if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-DO EMAIL #1"}
	}
	if {$alertonlyemail} {
		## nothing
	} else {
		## if alert only email is not switched on then send email anyway
		set doemail true
		if {$debuglvl>2} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-DO EMAIL #2"}
	}
	
	if {$doemail} {
		if {$emailsendrequired} {
			if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Email required"}
			
			if { [catch { sendmail $mailserver $domain $recipient "$ourSubject" $htmlfilename } fid] } {
				if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-FAILURE WHEN CALLING SENDMAIL FOR FIRST RECIPIENT >>$fid<<"}
				if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
				if {$::debuglvl>0} { puts "$errorInfo"}
				if {$::debuglvl>0} { puts "----------------------------------------------------------------"}	
			} else {
				if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Email sent"}
			}
			if { $recipient2 != "" } {
				if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-About to send mail to recipient 2"}
				if { [catch { sendmail $mailserver $domain $recipient2 "$ourSubject" $htmlfilename } fid] } {
					if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-FAILURE WHEN CALLING SENDMAIL FOR SECOND RECIPIENT >>$fid<<"}
					if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
					if {$::debuglvl>0} { puts "$errorInfo"}
					if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
				} else {
					if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Email sent to recipient 2"}
				}	
			}
			if { $recipient3 != "" } {
				if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-About to send mail to recipient 3"}
				if { [catch { sendmail $mailserver $domain $recipient3 "$ourSubject" $htmlfilename } fid] } {
					if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-FAILURE WHEN CALLING SENDMAIL FOR THIRD RECIPIENT >>$fid<<"}
					if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
					if {$::debuglvl>0} { puts "$errorInfo"}
					if {$::debuglvl>0} { puts "----------------------------------------------------------------"}
				} else {
					if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Email sent to recipient 3"}	
				}
			}
		} else {
			if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-Mail not required"}
		}
	} else {
		if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-EMAIL NOT SENT BECAUSE THERE IS NO ALERT DISCOVERED!"}
	}
	catch { unset doemail }
	if {$htmlfilerequired} {
		## nothing
	} else {
		if {$debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-HTML file generation not required"}
		file delete -force $htmlfilename
	}
	
	catch { unset tempTiVoName }
	
	if {$debuglvl>0} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-EMAIL & HTML FILE MANAGEMENT - COMPLETED"}

	## 190. END
	#########################################################################################


	# clear down variables 	
	foreach var [info vars] {
		catch {
			if {$var != "software_version" && $var != "software_release_date"} {
				if { [catch { 
					if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-unsetting variable >>$var<<"}
				} fid] } {
					# null
				} else {
					if { [catch { 
						unset $var  
					} fid] } {
						if {$::debuglvl>1} { puts "[clock format [clock seconds] -format {%H:%M:%S} -gmt true]-error in unsetting variable >>$var<<"}
					} 
				}
			}
		}
	}

puts ""
puts "------completed the jazzed dailymail program - v$software_version ($software_release_date) - thanks for your custom"
puts "------completed at [clock format [clock seconds] -format {%H:%M:%S} -gmt true]"
puts ""
puts ""


catch { unset software_version }
catch { unset software_release_date }




