A weird one, this won't work as folder attached script

G’day from oz

I’ve spent quite a few hours tracking this down, and can’t find an answer.

I’m reading mail from a particular mailbox, and have to double check that any particular mail hasn’t already been processed.

The problem arises in the ‘try’ statement. No matter how I use the variable ‘byPassPrint’, if it is reset within the ‘try’ statement then the ‘display dialog byPassPrint’ line hangs the script. It doesn’t hang if the variable is left as ‘continue’.

I’ve tried the variable as true and false, and as a number, but it still hangs.

The weird thing is the code works fine on it’s own, when not as an attached script. Something about the ‘try’ test stuffs the variable up.


on MainLoopTwo()
	tell application "Mail"
		repeat while (number of messages of mailbox MailBoxName) > 0
			set CycleThroughMessages to last message of mailbox MailBoxName
			if RunForOz then say "main loop"
			set EveryMailboxList to mailboxes
			repeat with testBoxName in EveryMailboxList
				if (name of testBoxName as string) ≠ MailBoxName then
					set selected mailboxes of message viewers to {mailbox (name of testBoxName as string)}
					exit repeat
				end if
			end repeat
			--set frontmost of application "Mail" to true
			set byPassPrint to "continue"
			try
				if (exists CycleThroughMessages) in mailbox MailBoxName then
					set TheName to the (id of CycleThroughMessages) & ".emlx" as string
					if my CheckThePausedReference(TheName) then
						set byPassPrint to "bypassprint"
						my TransferToITMP(CycleThroughMessages, true)
					end if
				else
					set byPassPrint to "bypassprint"
				end if
			on error TheError number errNum
				say "oooooops, can't set i d"
				set TheName to ""
				set byPassPrint to "bypassprint" 
			end try
			if RunForOz then say "main loop continues"
			display dialog byPassPrint
		end repeat
	end tell
	set TimeToElapse to my seeiftimehaselapsed("Check if elapsed")
	if TimeToElapse = "" then -- No time stored, so check if to recycle
		say "Checking recycle"
		tell application "Mail"
			set TemporaryMail2 to messages of mailbox MailBoxName
		end tell
		if (count of TemporaryMail2) > 0 then my MainLoopTwo()
	end if
end MainLoopTwo

Model: intel iMac
Browser: Safari 525.18
Operating System: Mac OS X (10.5)

I’ve tried various versions of the script, and it boils down to this,

as soon as a second loop of the scripts subroutine is used, the variable assigned to the theName can only be used once, then the script halts until the folder action re-triggers a refresh. Even if I set another variable to theName, as I’ve done below, the script hangs on using either the theName variable, or the reassigned one.

I’m at wit’s end on this, and would please appreciate any suggestions at all. I suspect a bug, though.

I’ll post the whole script if requested, but it’s over 2000 lines!!!


on MainLoopTwo(this_folder)
	tell application "Mail"
		activate
		repeat while (number of messages of mailbox MailBoxName) > 0
			set frontmost of application "Mail" to true
			if RunForOz then say "main loop"
			set EveryMailboxList to mailboxes
			(*repeat with testBoxName in EveryMailboxList
					set selected mailboxes of message viewers to {mailbox MailBoxName}
					if (name of testBoxName as string) ≠ MailBoxName then
						set selected mailboxes of message viewers to {mailbox (name of testBoxName as string)}
						exit repeat
					end if
				end repeat*)
			set CycleThroughMessages to last message of mailbox MailBoxName
			tell application "Mail"
				activate
				set TheName to the (id of CycleThroughMessages & ".emlx" as string)
				set frontmost of application "Mail" to true
				(*try
				if (exists CycleThroughMessages) in mailbox MailBoxName then 
				if my CheckThePausedReference(TheName) then
						set byPassPrint to true
						my TransferToITMP(CycleThroughMessages, true)
					end if
				else
					set byPassPrint to true
				end if
			on error TheError number errNum
				say "oooooops, can't set i d"
				set TheName to ""
				set byPassPrint to true
			end try*)
				set thetempname to TheName
				display dialog (count of TheName)
				tell application "System Events"
					try
						tell application "Mail" to display dialog thetempname
						tell application "Mail" to display dialog thetempname
					on error
						say "error"
					end try
				end tell
				if RunForOz then say "main loop continues"
				my MainLoopThree(CycleThroughMessages)
			end tell
		end repeat
	end tell
	set TimeToElapse to my seeiftimehaselapsed("Check if elapsed")
	if TimeToElapse = "" then -- No time stored, so check if to recycle
		say "Checking recycle"
		tell application "Mail"
			set TemporaryMail2 to messages of mailbox MailBoxName
		end tell
		if (count of TemporaryMail2) > 0 then my MainLoopTwo(this_folder)
	end if
end MainLoopTwo

Model: intel iMac
Browser: Safari 525.18
Operating System: Mac OS X (10.5)

OK, out of frustration I’ve stripped out half the code and will try and post it.

Anyone kind enough to run it must

  1. first create a mail folder called “* items to shift”

  2. Alter the short piece of script after the ‘Set to suit’ comment, to set your printer and email address.

  3. Then the script must be saved in the main Library/Scrips/Folder Action Scripts.

  4. Then, the script must be attached as a Folder Action to the ‘messages’ folder INSIDE the actual “* items to shift.mbox” mail folder which is in…
    /Library/Mail/Mailboxes.

  5. Enable ‘Access for Assistive devices’ in the ‘Universal Access’ control panel.

Now, drop some mail on the ‘* items to shift’ mail box. The second item should freeze after showing the ID once. The mail won’t disappear, but will be shifted to a newly created dated mail folder.

Thanks in advance

Santa

Damn, I’ve tried to post it but it’s too long, way over 65,500 characters.

If there’s anyone willing to test it then send me an email at bec9@tpg.com.au and I’ll send you a compressed copy.

Pity we can’t post compressed archives on this forum.

EDIT I’ll break it down into sections and post them sequentially. Hope it’s not a breach of rules?

Regards

Santa

Model: intel iMac
Browser: Safari 525.18
Operating System: Mac OS X (10.5)

SECTION 1




(*    Mail Item mover

Use as a Folder Action attached to a dedicated Mail folder, Called

             * items to shift
	
NOTE that the script must be attached to the 'Messages' folder 
INSIDE the ACTUAL Mail Folder.

The path to the folder is

Username/Library/Mail/Mailboxes/* items to shift/Messages OR
Username/Library/Mail/Mailboxes/Name_of_your_mailbox/Messages

When mail is dropped on, or shifted into (with a Mail rule), the Mail folder, they are 
first saved as rich text documents, with embedded attachments, then the rtf's are copied to... 

1/ a yearly storage folder on the server, with sub-folders based on the Daily date

2/ a daily, date-orientated folder on the server

3/ a daily folder on the Desktop

The message is then printed.
Once as a 'Cover sheet',  with headers, list of attachments, and the content
second, the attachments are printed on a separate printer.

Some parts of this script are derived from Apple inc's example scripts
Some parts of this script are derived from scripts available at MacScripter.net

Brian Christmas
bec9@tpg.com.au

Version 4.0 (trial Leopard version)
*)
-- Alter this property to reflect the name of the Mail box folder
property MailBoxName : "* items to shift"

-- Set the name of the server disk here...
property TheServerDisk : "TAZ.VOL1"

-- set the name of the Cover Page printer here...
property TheCoverPagePrinter : "HP LaserJet 5000 Series Art"

-- set the name of the pdf printer here...
property TheMainPrinter : "150.2.0.28"

property TheVirtualPrinter : "Virtual Printer"

-- Set the name of the pdf printing program here.
-- Note that this might be re-set in the script
property WhatToPrintpdfWith : "Adobe Acrobat Professional"

-- Set this to true or false
property WriteTheErrors : true

-- Set this to true or false
property SpeakTheErrors : true

-- Set the name of the voice to either "Agnes" "Kathy" "Princess" "Vicki" "Victoria" or
-- Set the name of the voice to either "Bruce" "Fred" "Junior" "Ralph"
property TheVoice : "Vicki"

-- Set the rate of speech to suit (between 130 and 210)
-- The higher the number, the faster the speech
property TheSpeechRate : 160

-- Set this to the required maximum number of Attachment pages to print.
-- Must be from 1 to 9
property MaxAttachmentPages : 3

-- This is the email address that error messages will be sent to.
property the_mailto : "**********@mac.com"

-- set the following to null string "" if not required
property Emergency_Contact : "**********@mac.com"

-- Set the following for the number of minutes to stop printing
property theMinutesToStop : 10

property TheBusinessName : "Santa Enterprises"

property RunForOz : true

property CheckCoverlist : {}
property CheckAttachmentList : {}
property CheckFileList : {}
property ExtensionsToIgnore : {"scr", "vcf", "gif"}
property DarnWindowsIllegalCharacters : {"?", "[", "]", "/", "=", "+", "<", ">", ":", ",;", ",", "*", ",|", "^", "\\", "\""}
property TrashEmptyNumber : 200
property byPassPrint : false
property TheName : ""

global ServerFolder
global Daily_Server_Folder
global Yearly_Server_Folder
global Yearly_Desktop_Folder
global Unrecognized_Server_Folder
global DidItPrint
global holding_folder
global NewFontInstalled
global PrintDateTimeName
global BarCodeDateTimeName
global DateTimeName
global theSendersFullName
global ErrorMessage
global printFilePath
global FileSavingErrorMessage
global ItMPmailerror
global CoverPagePrintingmailerror
global AddOnTime
global GlobalAMessage
global RTFName
global RTFPath
global TimeToStop
global theEntireSeconds
global StoreMonth
global WorkingDate
global theZeroedDate
global PathToDesktop
global this_folder


on adding folder items to this_folder after receiving first_added_items
	--“““““““““““““““““““““““““““““““““““““““““““““““““““““““““““““““““““
	--“““““““““““““““““““  Set to suit “““““““““““““““““““““““““““““““““““““““
	if RunForOz then
		set TheMainPrinter to "Epson Stylus Photo R390"
		set TheCoverPagePrinter to "Epson Stylus Photo R390"
		set the_mailto to "bec9@tpg.com.au"
		set Emergency_Contact to "bec9@tpg.com.au"
		--““““““““““““““““““““““““““““““““““““““““““““““““““““““““““““““““
		set TheServerDisk to ""
	end if
	tell application "Finder"
		if TheServerDisk ≠ "" then
			if not (exists the disk TheServerDisk) then
				try
					do shell script "diskutil mount `disktool -l | grep '" & TheServerDisk & "' | sed 's/.*\\(disk[0-9s]*\\).*/\\1/'`"
					delay 2
				end try
			end if
		end if
	end tell
	
	my FirstLoop(this_folder)
	if SpeakTheErrors and not TimeToStop then say "[[rate " & TheSpeechRate & "]] finished" using TheVoice
	
	
	-- This code warns if the server disk is getting low on space.
	-- We can't use a dialog box, unless we bring the Finder to the front
	tell application "Finder"
		try
			if exists disk TheServerDisk then
				set free_bytes to free space of disk TheServerDisk -- the number of free bytes left on the disk
				set free_Gbytes to (free_bytes / (1024 * 1024 * 0.1024) div 100) / 100
				if free_Gbytes < 10 then
					if SpeakTheErrors then say "[[rate " & TheSpeechRate & "]]warning, there are only " & free_Gbytes & " gigabytes left on server. " using TheVoice
					set frontmost of application "Finder" to true
					display dialog "There are only " & free_Gbytes & "GB left on the server" as string buttons {"OK"} giving up after 4
				end if
			end if
		end try
	end tell
	-- This code warns if the Boot disk is getting low on space.
	-- We can't use a dialog box, unless we bring the Finder to the front
	set TheDesktopDisk to (path to startup disk) as text
	set TheDesktopDisk to text 1 thru -2 of TheDesktopDisk
	tell application "Finder"
		try
			set TrashCount to every item of the trash
			set free_bytes to free space of disk TheDesktopDisk -- the number of free bytes left on the disk
			set free_Gbytes to (free_bytes / (1024 * 1024 * 0.1024) div 100) / 100
			if free_Gbytes < 10 then
				if SpeakTheErrors then say "[[rate " & TheSpeechRate & "]]warning, there are only " & free_Gbytes & " gigabytes left on the disk, " & TheDesktopDisk using TheVoice
				set frontmost of application "Finder" to true
				display dialog "There are only " & free_Gbytes & "GB left on the disk " & TheDesktopDisk as string buttons {"OK"} giving up after 4
			end if
		end try
	end tell
	-- This code checks the trash, and auto empties it if too full.
	try
		if (count of TrashCount) > (TrashEmptyNumber - 1) then
			if SpeakTheErrors then say "[[rate " & TheSpeechRate & "]]  The trash is overflowing. I'm emptying it automatically" using TheVoice
			tell application "Finder"
				try
					empty trash with option
				end try
			end tell
		end if
	end try
end adding folder items to

on FirstLoop(this_folder)
	set PathToDesktop to path to desktop as Unicode text
	tell application "Finder"
		try
			set ServerFolderExists to true
			try
				set ServerFolder to (folder "!preflight_art" of folder "Art Dept" of disk TheServerDisk) as alias
			on error
				set ServerFolderExists to false
			end try
			tell application "Mail"
				if exists mailbox "* items to manually process" then
					try
						set temp to messages of mailbox "* items to manually process"
						if number of items of temp = 0 then delete mailbox "* items to manually process"
					end try
				end if
			end tell
		end try
	end tell
	if ServerFolderExists or TheServerDisk = "" then
		my MainLoop(this_folder)
	else
		display dialog "It appears that the necessary folders on the server do not exist."
		set ErrorMessage to ErrorMessage & "Emergency!" & return & return & "The necessary files on the Server do not exist, or the Server is off." & return
		my MoveHoldingFolderToUnrecognizedItems()
	end if
end FirstLoop

--__________________________________  Main processing loops  ________________________________________

on MainLoop(this_folder)
	tell application "Mail"
		activate
		tell application "System Events" to tell process "Mail"
			set W to every window
			repeat with A in W
				tell A
					try
						if name of A = "Activity Viewer" then click button 1 of A
					end try
					try
						if name of A = "Addresses" then click button 1 of A
					end try
					try
						if name of A = "Mail Connection Doctor" then click button 1 of A
					end try
					try
						if name of A = "Previous Recipients" then click button 1 of A
					end try
					try
						if name of A = "Photo Browser" then click button 1 of A
					end try
				end tell
			end repeat
		end tell
		set TemporaryMail to messages of mailbox MailBoxName
		
		if SpeakTheErrors and RunForOz then say "[[rate " & TheSpeechRate & "]] there are " & (count of TemporaryMail) & " items to process." using TheVoice
	end tell
	my MainLoopTwo(this_folder)
end MainLoop

on MainLoopTwo(this_folder)
	tell application "Mail"
		activate
		repeat while (number of messages of mailbox MailBoxName) > 0
			set frontmost of application "Mail" to true
			if RunForOz then say "main loop"
			set EveryMailboxList to mailboxes
			repeat with testBoxName in EveryMailboxList
				set selected mailboxes of message viewers to {mailbox MailBoxName}
				if (name of testBoxName as string) ≠ MailBoxName then
					set selected mailboxes of message viewers to {mailbox (name of testBoxName as string)}
					exit repeat
				end if
			end repeat
			set CycleThroughMessages to last message of mailbox MailBoxName
			tell application "Mail"
				activate
				set TheName to the (id of CycleThroughMessages & ".emlx" as string)
				set frontmost of application "Mail" to true
				try
					if (exists CycleThroughMessages) in mailbox MailBoxName then
						if my CheckThePausedReference(TheName) then
							set byPassPrint to true
							my TransferToITMP(CycleThroughMessages, true)
						end if
					else
						set byPassPrint to true
					end if
				on error TheError number errNum
					say "oooooops, can't set i d"
					set TheName to ""
					set byPassPrint to true
				end try
				set thetempname to TheName
				tell application "System Events"
					try
						tell application "Mail" to display dialog thetempname
						
						--“““““““““““““““““““““““““““““““““““““““““““““““““““““““““““““““““
						
						-- Next line after second loop fails after previous line.
						-- 'On Error' does not trap error
						-- Script simply stops
						tell application "Mail" to display dialog thetempname
						
						--“““““““““““““““““““““““““““““““““““““““““““““““““““““““““““““““““
						
					on error
						say "error"
					end try
				end tell
				if RunForOz then say "main loop continues"
				my MainLoopThree(CycleThroughMessages)
			end tell
		end repeat
	end tell
	set TimeToElapse to my seeiftimehaselapsed("Check if elapsed")
	if TimeToElapse = "" then -- No time stored, so check if to recycle
		say "Checking recycle"
		tell application "Mail"
			set TemporaryMail2 to messages of mailbox MailBoxName
		end tell
		if (count of TemporaryMail2) > 0 then my MainLoopTwo(this_folder)
	end if
end MainLoopTwo

on MainLoopThree(CycleThroughMessages)
	if RunForOz then say "main loop continues two"
	if not my CheckTheFinishedReference(TheName) and not byPassPrint then -- Now, Check if time delay is active, or ask if not
		tell application "Finder"
			set frontmost of application "Finder" to true
			set TimeToStop to true
			set TheTally to my ReadRunningTally()
			set TimeToElapse to my seeiftimehaselapsed("Check if elapsed")
			if TimeToElapse ≠ "" then -- Must be a timestored, so ask if to continue
				set theMinutes to TimeToElapse div 60
				set theSeconds to TimeToElapse - (theMinutes * 60)
				if TimeToElapse > 0 then
					--if SpeakTheErrors then say "[[rate " & TheSpeechRate & "]]  We will  resume printing in " & theMinutes & " minutes and " & theSeconds & " seconds." using TheVoice
					set buttonname to "Stop another " & theMinutesToStop
					
					display dialog ¬
						"Total mail items printed : " & item 1 of TheTally & return & ¬
						"Total mail for yesterday : " & item 2 of TheTally & return & ¬
						"Running total for today  : " & item 3 of TheTally & return & return & ¬
						"Do you want to restart printing?" & return & return & ¬
						"Printing will resume automatically after " & theMinutes & " minutes and " & theSeconds & " seconds, after new mail arrives." buttons {"Restart", "Stay Stopped", buttonname} default button 2 giving up after 20
					set tempbutton to the button returned of the result
					if tempbutton = "Restart" then
						my seeiftimehaselapsed("Reset to empty")
						set TimeToStop to false
					else
						if tempbutton = buttonname then
							my seeiftimehaselapsed("Reset countdown")
							if SpeakTheErrors then say "[[rate " & TheSpeechRate & "]]  Stopping for another " & theMinutesToStop & " minutes." using TheVoice
						end if
					end if
				end if
			else
				display dialog ¬
					"Overall mail items printed : " & item 1 of TheTally & return & ¬
					"Total mail for yesterday    : " & item 2 of TheTally & return & ¬
					"Running total for today     : " & item 3 of TheTally & return & return & ¬
					"Do you want to stop printing for " & theMinutesToStop & " minutes, " & return & return & ¬
					"OR" & return & return & ¬
					"Continue printing." buttons {"Stop", "Continue"} default button 2 giving up after 10
				if the button returned of the result is "Stop" then
					my seeiftimehaselapsed("Reset countdown")
					if SpeakTheErrors then say "[[rate " & TheSpeechRate & "]]  Stopping for " & theMinutesToStop & " minutes." using TheVoice
				else
					my seeiftimehaselapsed("Reset to empty")
					set TimeToStop to false
				end if
			end if
		end tell
		if TimeToStop then
			if RunForOz then say "Stopping"
			exit repeat
		end if
		set DidItPrint to true
		set ItMPmailerror to false
		set CoverPagePrintingmailerror to false
		set theSubject to "No Subject"
		set ErrorMessage to ""
		set FileSavingErrorMessage to ""
		set AddOnTime to 0
		set theSendersFullName to ""
		
		set thePrintName to TheName
		set byPassCheck to false
		
		-- Check if the item has been started before, and if so, is it completed
		
		if my CheckTheStartingReference(TheName) and not my CheckTheFinishedReference(TheName) then
			tell application "Finder"
				display dialog ¬
					"Total mail items printed : " & item 1 of TheTally & return & ¬
					"Total mail for yesterday : " & item 2 of TheTally & return & ¬
					"Running total for today  : " & item 3 of TheTally & return & return & ¬
					"It appears that the mail item " & TheName & " has tried to be processed before, and has stopped during attachment printing." & return & return & ¬
					"Do you want to try and process it again," & return & return & ¬
					"OR" & return & return & ¬
					"Move it to the Mailbox '* items to manually process'." buttons {"Retry processing", "Move to Mailbox"} default button 2 giving up after 10
				set temp to the button returned of the result
				if temp = "Move to Mailbox" or temp = "" then
					try
						set byPassCheck to true
						my TransferToITMP(CycleThroughMessages, false)
						my SaveThePausedReference(TheName)
					end try
				end if
			end tell
		end if
		if not byPassCheck and not my CheckTheFinishedReference(TheName) then
			tell application "Mail"
				set theSendersFullName to (the sender of CycleThroughMessages) as string
				set theSender to theSendersFullName
				if length of theSender > 30 then set theSender to text 1 thru 30 of theSender
				set temp to (the subject of CycleThroughMessages) as string
				if temp ≠ "" then set theSubject to temp
			end tell
			
			-- we must only refer to date & time ONCE
			-- This routine get Universal Time
			copy (current date) - (time to GMT) to WorkingDate
			copy WorkingDate to theZeroedDate
			set the time of theZeroedDate to 0 -- set to midnight
			
			set theEntireSeconds to time of WorkingDate -- the day time in seconds
			
			-- We'll loop this until no files match
			-- in case of daylight saving duplication, or computer time re-setting
			tell application "Finder"
				repeat
					try
						set {theMonth, theDays, theHours, theMinutes, theSeconds, DateTimeName} to my SetDateTimeName(theEntireSeconds, WorkingDate)
						
						set PrintDateTimeName to (year of WorkingDate & "-" & theMonth & "-" & theDays as string) & " " & theHours & theMinutes & theSeconds & "Z"
						set BarCodeDateTimeName to "(" & (year of WorkingDate & " " & theMonth & " " & theDays & " " as string) & theHours & " " & theMinutes & " " & theSeconds & "Z)"
						set FolderDailyName to (year of WorkingDate & " " & theMonth & " " & theDays as string)
						set TheYear to year of WorkingDate as string
						-- Now make all the necessary folders
						-- First a Daily, and a Yearly, and the Unrecognized, folder on Server
						if TheServerDisk ≠ "" then
							if not (exists folder "Daily Email Orders" of ServerFolder) then
								make new folder at ServerFolder with properties {name:"Daily Email Orders"}
							end if
							set the Daily_Server_Folder to (folder "Daily Email Orders" of ServerFolder) as alias
							set the Yearly_Server_Folder to "Yearly Email Orders " & year of WorkingDate
							if not (exists folder Yearly_Server_Folder of ServerFolder) then
								make new folder at ServerFolder with properties {name:Yearly_Server_Folder}
							end if
							if not (exists folder "Unrecognized items" of ServerFolder) then
								make new folder at ServerFolder with properties {name:"Unrecognized items"}
							end if
							set the Unrecognized_Server_Folder to (folder "Unrecognized items" of ServerFolder) as alias
						end if
						say "daily folders"
						
						-- Now, Check and create DAILY folders
						-- First on desktop
						set Yearly_Desktop_Folder to "Yearly Orders " & year of WorkingDate
						if not (exists folder Yearly_Desktop_Folder of desktop) then
							make new folder at desktop with properties {name:Yearly_Desktop_Folder}
						end if
						if not (exists folder FolderDailyName of folder Yearly_Desktop_Folder of desktop) then
							make new folder at folder Yearly_Desktop_Folder of desktop with properties {name:FolderDailyName}
						end if
						-- Then, on server in yearly folder
						if TheServerDisk ≠ "" then
							if not (exists folder FolderDailyName of folder Yearly_Server_Folder of ServerFolder) then
								make new folder at folder Yearly_Server_Folder of ServerFolder with properties {name:FolderDailyName}
							end if
						end if
						-- Now folder for temporary rtf's
						if not (exists folder "RTF Documents" of desktop) then make new folder with properties {name:"RTF Documents"}
						
						if TheServerDisk ≠ "" then
							set Year_Day_Server_Folder to (folder FolderDailyName of folder Yearly_Server_Folder of ServerFolder) as string
						end if
						
						-- Now check Mac for any existing daily file of same name
						set Year_Day_Folder to (folder FolderDailyName of folder Yearly_Desktop_Folder) as string
						my CheckIfFileExists(Year_Day_Folder, DateTimeName, "rtfd")
						
						if AddOnTime = 0 then
							exit repeat
						else
							set theEntireSeconds to theEntireSeconds + AddOnTime
						end if
					on error TheError number errNum
						set ErrorMessage to ErrorMessage & "Emergency" & return & "A major problem has occurred while creating folders." & return & "It appears likely that the server is acting up, or is down." & return & "It needs fixing ASAP." & return
						set PrintError to "There is a Folder creation problem" & return & return & TheError & return & return
						if WriteTheErrors then my WriteErrors(PrintError, errNum)
						exit repeat
					end try
				end repeat
				-- These are used for file renaming & saving
				set RTFName to PrintDateTimeName & ".rtfd"
				set ShortRTFName to PrintDateTimeName & ".rtf"
				
				-- These are used for printing
				if TheServerDisk ≠ "" then
					set theFilePath2 to folder Daily_Server_Folder as string
					set printFilePath to theFilePath2 & DateTimeName
				end if
				set dest_folder to PathToDesktop & "Temporary Printing:" as string
				if not (exists folder dest_folder) then make new folder with properties {name:"Temporary Printing"}
				set holding_folder to dest_folder & PrintDateTimeName & ":" as string
				if not (exists folder holding_folder) then make new folder at folder dest_folder with properties {name:PrintDateTimeName}
				-- Do any desired stuff to message here, before moving (actually copying)
				tell application "Mail"
					try -- *** PRINTING ***
						activate
						open CycleThroughMessages
						set tempWindowName to subject of CycleThroughMessages & " ” " & MailBoxName as string
						set x to 0
						tell application "System Events" to tell process "Mail"
							repeat
								if exists window tempWindowName then exit repeat
								delay 1
								set x to x + 1
								if x = 5 then exit repeat -- Cycle for 5 seconds if window doesn't open
							end repeat
							set frontmost of application "Mail" to true
							keystroke "s" using {command down, shift down}
							tell window 1
								-- NOTE: A problem arises when the emails 'Subject' field is blank
								--           so we must use 'try' to select field
								delay 0.2
								try
									select text field 1 of sheet 1
								end try
								delay 0.2
								keystroke RTFName
								delay 0.2
								try
									tell pop up button 1 of sheet 1
										click
										delay 0.5
										tell menu 1
											click menu item "Desktop"
										end tell
									end tell
								end try
								try
									if value of checkbox "Include Attachments" of group 1 of sheet 1 = 0 then click checkbox "Include Attachments" of group 1 of sheet 1
								end try
								try
									tell group 1 of sheet 1
										tell pop up button 1
											click
											delay 0.2
											tell menu 1
												click menu item 1
											end tell
										end tell
									end tell
								end try
							end tell
							tell window 1
								delay 0.2
								click button "Save" of sheet 1
								delay 0.2
								keystroke return
								delay 0.2
								keystroke return
								delay 0.2
								keystroke return
								delay 0.2
							end tell
						end tell
						close window 1
						tell application "Finder"
							get every item of desktop -- To refresh the finder
							
							set x to 0
							repeat
								if exists file ShortRTFName then
									set the name of file ShortRTFName to RTFName
									get every item of desktop
								end if
								if exists file PrintDateTimeName then
									set the name of file PrintDateTimeName to RTFName
									get every item of desktop -- To refresh the finder
								end if
								delay 1
								if exists file RTFName then exit repeat
								get every item of desktop
								delay 1
								set x to x + 1
								if x = 5 then exit repeat -- wait 10 seconds
							end repeat
							get every item of desktop -- To refresh the finder
							move file RTFName to folder "RTF Documents"
							
							get every item of desktop -- To refresh the finder
							set RTFPath to PathToDesktop & "RTF Documents:" & RTFName as string
							set AlterRTFPath to PathToDesktop & "RTF Documents:" & PrintDateTimeName as string
							set x to 0
							repeat
								if exists file AlterRTFPath then set the name of file AlterRTFPath to RTFName
								if exists file RTFPath then exit repeat
								delay 1
								set x to x + 1
								if x = 15 then
									set frontmost of application "Finder" to true
									display dialog "Error in shifting file 2" giving up after 30
									exit repeat -- wait 15 seconds
								end if
							end repeat
							delay 2
						end tell
						
					on error TheError number errNum
						set PrintError to "There is a problem with the routine preparing the rtf Content: " & return & return & TheError & return & return
						if WriteTheErrors then my WriteErrors(PrintError, errNum)
					end try
				end tell -- end tell mail
				
				-- Now go and print the Cover Sheet
				my PrintTheDarnThing(CycleThroughMessages)
				
				-- NOW, save the files
				-- copy and set ready to trash
				set TryToSave to true
				if exists file RTFPath then
					try
						--Now copy to Desktop --note we use 'duplicate' this time,
						-- because we're copying to the same disk.
						duplicate file RTFPath to folder FolderDailyName of folder Yearly_Desktop_Folder of desktop
					on error errMsg number errNum
						set PrintError to "There is a 'Saving File' problem saving to the Mac: " & return & return & errMsg & return & return
						if WriteTheErrors then my WriteErrors(PrintError, errNum)
						if SpeakTheErrors then say "[[rate " & TheSpeechRate & "]]There is a File Saving problem with saving the File to the Macintosh. " & id of CycleThroughMessages using TheVoice
						set ErrorMessage to ErrorMessage & "There was a file saving problem with saving the file to the Mac." & return
						set TryToSave to false
					end try
					
					if TheServerDisk ≠ "" then
						try
							--Now copy to Yearly server storage
							duplicate file RTFPath to Year_Day_Server_Folder
						on error errMsg number errNum
							set PrintError to "There is a 'Saving File' problem saving to the Server Year Day folder: " & return & return & errMsg & return & return
							if WriteTheErrors then my WriteErrors(PrintError, errNum)
							if SpeakTheErrors then say "[[rate " & TheSpeechRate & "]]There is a File Saving problem with saving the File to the Server Yearly folder. " & id of CycleThroughMessages using TheVoice
							set ErrorMessage to ErrorMessage & "There was a file saving problem with saving the file to the Server Year Day folder." & return
							set TryToSave to false
						end try
						
						try
							--Now copy to Daily server storage
							duplicate file RTFPath to Daily_Server_Folder
						on error errMsg number errNum
							set PrintError to "There is a 'Saving File' problem saving to the Server Daily Folder: " & return & return & errMsg & return & return
							if WriteTheErrors then my WriteErrors(PrintError, errNum)
							if SpeakTheErrors then say "[[rate " & TheSpeechRate & "]]There is a File Saving problem with saving the File to the server daily folder. " & id of CycleThroughMessages using TheVoice
							set ErrorMessage to ErrorMessage & "There was a file saving problem with saving the file to the Server Daily folder." & return
							set TryToSave to false
						end try
					end if
					
				end if
				if not TryToSave then my TransferToITMP(CycleThroughMessages, true)
				
				-- Did the first printing take place?, then save the name of the
				-- document as having gone through the cover page system
				my SaveTheStartingReference(TheName)
				
				
				
				-- Now go and print the Attachments
				--if DidItPrint then my SecondAttachmentPrintCycle()
				
				
				
				-- NOW! What do we do with Attachment folder?
				try
					if ErrorMessage = "" and FileSavingErrorMessage = "" then
						if exists folder holding_folder then move folder holding_folder to trash
					else
						my MoveHoldingFolderToUnrecognizedItems()
					end if
					
					set TemporaryPrintingPath to PathToDesktop & "Temporary Printing" as string
					
					set label index of folder "Temporary Printing" to 0
					repeat with x in (get every item of folder TemporaryPrintingPath)
						if class of x is folder then
							set c to (get every item of x)
							if c = {} then
								move x to trash
							else
								set label index of folder "Temporary Printing" to 2
							end if
						end if
					end repeat
					tell application "Mail"
						try
							set TempSubject to subject of CycleThroughMessages as text
							if not DidItPrint then
								my TransferToITMP(CycleThroughMessages, true)
							else
								set TempYearString to "Year " & TheYear
								if not (exists mailbox TempYearString) then make new mailbox with properties {name:TempYearString}
								if not (exists mailbox FolderDailyName) of mailbox TempYearString then make new mailbox with properties {name:TempYearString & "/" & FolderDailyName}
								move CycleThroughMessages to mailbox FolderDailyName of mailbox TempYearString
							end if
						end try
					end tell
					delay 1
					
					-- Now, the curtain call, the files done it's job.
					move file RTFPath to trash -- if this succeeds, the other two follow on.
					my SaveAllTheData(TempSubject, FolderDailyName, TheYear)
					my SaveTheFinishedReference(TheName)
					set label index of folder "RTF Documents" to 0
					set temp to every item of folder "RTF Documents"
					if temp ≠ {} then set label index of folder "RTF Documents" to 2
				on error
					say "Error whilst removing files"
					
					-- do nuttin
				end try
			end tell -- end tell finder
			my SetRunningTally(TheYear, theMonth, theDays)
		end if
	else
		if RunForOz then say "Bypassed"
	end if
end MainLoopThree

--__________________________________  Cover Page Printing  ________________________________________

on PrintTheDarnThing(CycleThroughMessages)
	tell application "Finder"
		-- Wait for printer
		if RunForOz then say "testing printer"
		my TestPrinterStatus(TheCoverPagePrinter)
		if RunForOz then say "printer tested"
		
		if DidItPrint then -- No printer error? then proceed to print.
			tell application "Printer Setup Utility"
				copy current printer to CurrentPrinter
				set current printer to printer TheCoverPagePrinter of application "Printer Setup Utility"
			end tell
			
			tell application "Mail"
				try
					-- Now to list attachments
					set theAttachmentNames to "Attachments for " & TheName & return & return
					set AttachmentWarningCount to 0
					set AttachmentWarning to ""
					set CountOftheAttachmentNames to 0
					if (count of CycleThroughMessages's mail attachments) = 0 then
						set theAttachmentNames to theAttachmentNames & "<None>" & return
						set CountOftheAttachmentNames to 1
					end if
					repeat with theAttachment in CycleThroughMessages's mail attachments
						set AName to "<" & theAttachment's name & ">"
						set theAttachmentNames to theAttachmentNames & AName & return
						set CountOftheAttachmentNames to CountOftheAttachmentNames + 1
						if "." is not in characters -6 thru -2 of AName then set AttachmentWarningCount to AttachmentWarningCount + 1
					end repeat
					if AttachmentWarningCount = 1 then set AttachmentWarning to "Warning! There is an attachment in this email without a name extension."
					if AttachmentWarningCount > 1 then set AttachmentWarning to "Warning! There are " & AttachmentWarningCount & " attachments in this email without name extensions."
					
					-- *** This prepares cover page, just as text. 
					--set printFilePath to my replace_chars(printFilePath, ":", ":   ") as string -- just to make more readable
					
					set TempSubject to subject of CycleThroughMessages as text
					if TempSubject = "" then set TempSubject to "<no subject>"
					set TheOpenAttachmentList to {}
					if TheOpenAttachmentList = {} then set TheOpenAttachmentList to "<None>" & return
					set theEmail to TheBusinessName & ¬
						return & ("Reference number : " & PrintDateTimeName & ¬
						return & BarCodeDateTimeName & ¬
						return & "File Path is... " & ¬
						return & "-----Excluded-----") & ¬
						return & "__________________________________________________________" & ¬
						return & ¬
						return & "From: " & (sender of CycleThroughMessages as text) & ¬
						return & "Subject: " & TempSubject & ¬
						return & "Date: " & (date sent of CycleThroughMessages as text) & ¬
						return & "__________________________________________________________" & ¬
						return & AttachmentWarning & ¬
						return & ¬
						return & theAttachmentNames & ¬
						return & "The list of opened Attachments...." & ¬
						return & ¬
						return & TheOpenAttachmentList & ¬
						return & "__________________________________________________________"
				end try
			end tell
		end if
	end tell
	
	tell application "TextEdit"
		activate
		try
			if RunForOz then say "opening r t f path"
			open RTFPath as alias
			--set text of document frontmost to theEmail & return & text of document frontmost
			set paragraph 1 of document frontmost to theEmail & return & paragraph 1 of document frontmost
			-- You can alter these 'set paragraph' lines.
			-- Just make sure the used font has a BOLD type set
			-- if you use -BOLD
			tell document frontmost
				set TotalParagraphs to (count of paragraphs of theEmail)
				set font of paragraphs 1 thru TotalParagraphs to "Times"
				set size of paragraphs 1 thru TotalParagraphs to 14
				set color of paragraphs 1 thru TotalParagraphs to {0, 0, 0}
				
				set font of paragraphs 1 thru 2 to "Times-Bold"
				set size of paragraphs 1 thru 2 to 20
				set color of paragraphs 1 thru 2 to {50411, 560, 2938} -- Change to {0,0,0} for black
				set font of paragraph 3 to "IDAutomationHC39M" -- Bar Code font
				set size of paragraph 3 to 14
				set font of paragraphs 4 thru 5 to "Times-Bold"
				set size of paragraphs 4 thru 5 to 14
				set color of paragraphs 4 thru 5 to {50411, 560, 2938}
				set font of word 1 of paragraph 8 to "Times-Bold"
				set size of word 1 of paragraph 8 to 15
				set font of word 1 of paragraph 9 to "Times-Bold"
				set size of word 1 of paragraph 9 to 15
				set font of word 1 of paragraph 10 to "Times-Bold"
				set size of word 1 of paragraph 10 to 15
				set font of paragraph 12 to "Times-Bold"
				set size of paragraph 12 to 16
				set color of paragraph 12 to {50411, 560, 2938}
				set font of paragraph 14 to "Times-Bold"
				set size of paragraph 14 to 16
				set color of paragraph 14 to {40626, 22439, 544}
				set font of paragraph (17 + CountOftheAttachmentNames) to "Times-Bold"
				set size of paragraph (17 + CountOftheAttachmentNames) to 16
				set color of paragraph (17 + CountOftheAttachmentNames) to {40626, 22439, 544}
			end tell
			tell application "Finder"
				try
					move file RTFPath to trash -- so we don't have to replacesave over it
				end try
			end tell
			tell application "System Events" to tell process "TextEdit"
				keystroke "s" using {command down, shift down}
				delay 1
				click pop up button 1 of group 1 of group 1 of sheet 1 of window 1
				delay 1
				click menu item 2 of menu 1 of pop up button 1 of group 1 of group 1 of sheet 1 of window 1
				delay 1
				click button "Save" of sheet 1 of window 1
				--delay 4
			end tell
			try
				close document frontmost without saving
			on error
				-- do nuttin
			end try
			try
				open RTFPath as alias
			on error
				say "no rtf path"
			end try
			tell application "System Events" to tell process "TextEdit"
				delay 1
				keystroke "p" using command down
				tell window 1
					repeat until sheet 1 exists
						delay 0.1
					end repeat
					get value of checkbox 1 of sheet 1
					if it = 0 then click checkbox 1 of sheet 1
					click radio button 2 of radio group 2 of sheet 1
					repeat 7 times
						keystroke tab
						delay 0.1
					end repeat
					--delay 1
					keystroke MaxAttachmentPages as string
					delay 0.1
				end tell
				delay 1
				click button 1 of sheet 1 of window 1
			end tell
			delay 2
			tell application "TextEdit"
				try
					close document frontmost without saving
					delay 1
					close document frontmost without saving
				on error
					-- do nuttin
				end try
			end tell
			
		on error TheError number errNum
			set DidItPrint to false
			set PrintError to "There is an actual Printing problem with the Cover Page: " & return & return & TheError & return & return
			if WriteTheErrors then my WriteErrors(PrintError, errNum)
			if SpeakTheErrors then say "[[rate " & TheSpeechRate & "]]There is an actual Printing problem with the Cover Page." using TheVoice
			my TransferToITMP(CycleThroughMessages, false)
		end try
	end tell
	tell application "Printer Setup Utility"
		set current printer to CurrentPrinter
	end tell
	if RunForOz then say "printing cover sheet completed"
end PrintTheDarnThing

--__________________________________  Attachment Preparation  (2 sequential routines)  ______________________________

--   STRIPPED OUT


Model: intel iMac
Browser: Safari 525.18
Operating System: Mac OS X (10.5)

SECTION 2, APPEND TO SECTION 1



--__________________________________  Sub-routines  ________________________________________


-- The actual Printer testing routine
on TestPrinterStatus(PrinterName)
	tell application "Printer Setup Utility"
		try
			set DelayCycle to 1
			repeat
				delay 0.2
				set ThePrinterStatus to status of printer PrinterName as string
				if "idle" is in ThePrinterStatus or "constant ****prng" is in ThePrinterStatus then exit repeat
				if DelayCycle = 200 then
					if ThePrinterStatus = "printing" then
						if SpeakTheErrors then say "[[rate " & TheSpeechRate & "]]Waiting for Printer. " & PrinterName & ". to become available. " using TheVoice
						set DelayCycle to DelayCycle + 1
					end if
				end if
				if DelayCycle = 1 then
					if ThePrinterStatus = "error" then
						if SpeakTheErrors then say "[[rate " & TheSpeechRate & "]]There is an error with the printer. " using TheVoice
						delay 1
						if SpeakTheErrors then say "[[rate " & TheSpeechRate & "]]please check the printer. " & PrinterName using TheVoice
						set DelayCycle to DelayCycle + 1
					else
						
						if ThePrinterStatus = "stopped" then
							if SpeakTheErrors then say "[[rate " & TheSpeechRate & "]]The printing for printer. " & PrinterName & ". is stopped." using TheVoice
							delay 1
							if SpeakTheErrors then say "[[rate " & TheSpeechRate & "]]please check the printer status with. printer set up utility" using TheVoice
							set DelayCycle to DelayCycle + 1
						else
							if ThePrinterStatus ≠ "printing" then
								if SpeakTheErrors then say "[[rate " & TheSpeechRate & "]]There is an unknown error with printer. " & PrinterName using TheVoice
								delay 1
								if SpeakTheErrors then say "[[rate " & TheSpeechRate & "]]The actual error is." & ThePrinterStatus using TheVoice
								delay 1
								if SpeakTheErrors then say "[[rate " & TheSpeechRate & "]]please check the printer status with. printer set up utility" using TheVoice
								delay 0.5
								if SpeakTheErrors then say "[[rate " & TheSpeechRate & "]]or. the printer might not be turned on." using TheVoice
								if WriteTheErrors then my WriteErrors("Printer Error equals " & ThePrinterStatus & return, "None")
								tell application "Printer Setup Utility"
									quit
								end tell
								tell application "Printer Setup Utility"
									activate
								end tell
								set DelayCycle to DelayCycle + 1
							end if
						end if
					end if
				end if
				set DelayCycle to DelayCycle + 1
				if DelayCycle > 200 then set DelayCycle to 1
			end repeat
		on error TheError number errNum
			set DidItPrint to false
			set PrintError to "There is a Printer problem with printer " & PrinterName & return & return & TheError & return & return
			if WriteTheErrors then my WriteErrors(PrintError, errNum)
			if errNum = 1 then
				if SpeakTheErrors then say "[[rate " & TheSpeechRate & "]]The printer. " & PrinterName & ". does not exist, or is not available." using TheVoice
			end if
		end try
	end tell
end TestPrinterStatus

on CheckProcessIsOpen(TheApplication)
	tell application "Finder"
		try
			set temp to the name of every process as string
			if TheApplication is in temp then
				return true
			else
				set DidItPrint to false
				if SpeakTheErrors then say "[[rate " & TheSpeechRate & "]]The Application " & TheApplication & " appears to have quit." using TheVoice
				return false
			end if
		end try
	end tell
end CheckProcessIsOpen

on TransferToITMP(CycleThroughMessages, thesound)
	tell application "Mail"
		try
			if not (exists mailbox "* items to manually process") then
				make new mailbox with properties {name:"* items to manually process"}
			end if
			try
				set m to name of mailbox of CycleThroughMessages as string
				if m ≠ "* items to manually process" then
					move CycleThroughMessages to mailbox "* items to manually process"
					if SpeakTheErrors and thesound then say "[[rate " & TheSpeechRate & "]]The mail file has been transferred to the mail box, items to manually process." using TheVoice
					if thesound then set ItMPmailerror to true
				end if
			on error
				--do nuttin'
			end try
			--get messages of mailbox MailBoxName
		end try
	end tell
end TransferToITMP

on MoveHoldingFolderToUnrecognizedItems()
	tell application "Finder"
		try
			set bypassMove to true
			if ErrorMessage ≠ "" then
				try
					move file RTFPath to folder Unrecognized_Server_Folder -- Copy Onto Server
				on error
					set ErrorMessage to ErrorMessage & "Emergency" & return & "There is an error saving to the Unrecognizable Items folder to the server." & return & "This is a major error, and should be rectified ASAP." & return
				end try
				try
					if not (exists folder "Unrecognized items for Manual printing") then make new folder with properties {name:"Unrecognized items for Manual printing"}
					move folder holding_folder to trash
					duplicate file RTFPath to folder "Unrecognized items for Manual printing"
					set label index of folder "Unrecognized items for Manual printing" to 1
					if SpeakTheErrors then say "[[rate " & TheSpeechRate & "]]The rtf file, with attachments, has been moved to the folder, Unrecognized items for Manual printing. " using TheVoice
					set bypassMove to false
				on error
					set ErrorMessage to ErrorMessage & "Attention!" & return & "There is an error saving to the Unrecognizable Items folder on the desktop." & return & "This is a major error, and should be rectified ASAP." & return
				end try
			else
				if exists folder holding_folder then move folder holding_folder to trash
			end if
			
			-- this could add a null string
			set ErrorMessage to ErrorMessage & FileSavingErrorMessage
			
			set the_subject to "Alert! Order preparation problem."
			set the_content to my SetTheHeading() & ¬
				"Errors have been encountered while preparing an email Order for printing." & return & return & ¬
				"The errors are..." & return & return & ErrorMessage & return & return & ¬
				"The Order email is from " & theSendersFullName & "." & return & return
			if ItMPmailerror then set the_content to the_content & "The email has been shifted to the Mail folder 'Items to Manually Process'." & return & return
			set thetextflag to false
			if not bypassMove then
				set the_content to the_content & "The pdf file '" & RTFName & "' has been re-located into the folder 'Unrecognized items for Manual Printing'." & return & return
				set thetextflag to true
			end if
			if CoverPagePrintingmailerror then
				set the_content to the_content & "Particularly note that a cover page did not print, and the email has been shifted to the Mailbox 'Items to manually process'." & return
			else
				set the_content to the_content & "Please note that a cover sheet should have been printed." & return
			end if
			tell application "Mail"
				activate
				
				set newMessage to make new outgoing message with properties {address:the_mailto, subject:the_subject, content:the_content}
				tell newMessage
					set x to offset of TheBusinessName in the_content
					set font of characters x thru (x + (count of TheBusinessName)) of content to "Helvetica Bold"
					set color of characters x thru (x + (count of TheBusinessName)) of content to {56342, 2442, 607}
					set x to offset of ErrorMessage in the_content
					set font of characters x thru (x + (count of ErrorMessage)) of content to "Helvetica Bold"
					set color of characters x thru (x + (count of ErrorMessage)) of content to {35288, 1602, 1985}
					set x to offset of "'Items to Manually Process'" in the_content
					if x > 0 then set font of characters x thru (x + (count of "'Items to Manually Process'")) of content to "Helvetica Bold"
					set x to offset of PrintDateTimeName in the_content
					if x > 0 then set font of characters x thru (x + (count of PrintDateTimeName)) of content to "Helvetica Bold"
					if thetextflag then
						set x to offset of "'Unrecognized items for Manual Printing'." in the_content
						set font of characters x thru (x + (count of "'Unrecognized items for Manual Printing'.")) of content to "Helvetica Bold"
					end if
					make new to recipient with properties {address:the_mailto}
					send
				end tell
			end tell
			if "Emergency" is in the_content and Emergency_Contact ≠ "" and my seeifhourhaselapsed() then
				set the_subject to "EMERGENCY! Order preparation problem."
				set ErrorMessage to "PLEASE NOTE!"
				set the_content to "This is an automated message from the Art Room at " & TheBusinessName & return & return & ErrorMessage & return & return & "There has been a problem occur with the automated printing process." & return & return & "It appears we have a problem with the server, files are not saving. Please investigate it." & return & return & return & "NOTE that this message will be sent only once per hour until the problem is rectified." & return
				tell application "Mail"
					activate
					
					set newMessage to make new outgoing message with properties {address:Emergency_Contact, subject:the_subject, content:the_content}
					tell newMessage
						set x to offset of TheBusinessName in the_content
						set font of characters x thru (x + (count of TheBusinessName)) of content to "Helvetica Bold"
						set color of characters x thru (x + (count of TheBusinessName)) of content to {56342, 2442, 607}
						set x to offset of ErrorMessage in the_content
						set font of characters x thru (x + (count of ErrorMessage)) of content to "Helvetica Bold"
						set color of characters x thru (x + (count of ErrorMessage)) of content to {35288, 1602, 1985}
						make new to recipient with properties {address:Emergency_Contact}
						send
					end tell
				end tell
			end if
		on error TheError number errNum
			if errNum ≠ -1728 then display dialog errNum & return & "Error in MoveHoldingFolderToUnrecognizedItems" & return & TheError as string
		end try
	end tell
end MoveHoldingFolderToUnrecognizedItems

on SendABloodyTally(TheTally, theLastMidnight)
	set the_subject to "eMail Tally since " & year of theLastMidnight & " " & month of theLastMidnight & " " & day of theLastMidnight
	set TallyString to {"Computer processed data since " & theLastMidnight & "..."} & return & return & "Hour " & return
	
	set theLastTally to 0
	repeat with x from 1 to 24
		set thetemphour to item (3 + (x * 2)) of TheTally as string
		set theReadingTally to item (4 + (x * 2)) of TheTally as string
		set tempX to x as string
		-- This counts the hours, and adds space if below 10
		if (count of tempX) < 2 then set tempX to "_" & tempX as string
		-- This builds string of asterixes for each hour
		set GraphString to ""
		repeat with y from 1 to theReadingTally
			set GraphString to GraphString & "*"
		end repeat
		-- This add space if number below 10
		if (count of GraphString) < 10 then set theReadingTally to "_" & theReadingTally as string
		-- Build Tally string
		set end of TallyString to tempX & " : " & theReadingTally & "  " & GraphString & return
	end repeat
	set the_content to (my SetTheHeading() & ¬
		"Total Mail items processed : " & item 1 of TheTally as string) & return & return & ¬
		"Since " & theLastMidnight & " (Universal time), we computer processed..." & return & return & ¬
		"Total Mail for previous period : " & item 2 of TheTally & return & return & ¬
		the TallyString & return & return & ¬
		"Have a good day."
	tell application "Mail"
		activate
		set newMessage to make new outgoing message with properties {address:the_mailto, subject:the_subject, content:the_content}
		tell newMessage
			set x to offset of TheBusinessName in the_content
			set font of characters x thru (x + (count of TheBusinessName)) of content to "Helvetica Bold"
			set color of characters x thru (x + (count of TheBusinessName)) of content to {56342, 2442, 607}
			set y to offset of "Hour " in the_content
			repeat with x from y to count of the_content
				if character x of the_content = "*" then
					set color of characters x thru x of content to {56342, 2442, 607}
					delay 0.01
					set the size of characters x thru x of content to 24
				end if
			end repeat
			make new to recipient with properties {address:the_mailto}
			send
		end tell
	end tell
end SendABloodyTally

on SendMonthlyReport(theMonth, WholeList)
	set the_subject to "Processed eMail Tally for " & theMonth & "."
	set TallyString to {"Computer processed data for previous " & theMonth & " ..."} & return & return
	
	set theLastTally to 0
	set the MonthsTotal to 0
	repeat with x from 1 to ((number of items in WholeList) - 2) div 3
		set thetempmonth to item (0 + (x * 3)) of WholeList as string
		set thetempday to item (1 + (x * 3)) of WholeList as string
		set theReadingTally to item (2 + (x * 3)) of WholeList as string
		if thetempmonth = theMonth then
			set the MonthsTotal to MonthsTotal + theReadingTally
			set GraphString to ""
			repeat with y from 1 to (theReadingTally + 3) div 4
				set GraphString to GraphString & "*"
			end repeat
			set temp to the theReadingTally as string
			if (count of temp) < 2 then set temp to "__" & temp
			if (count of temp) < 3 then set temp to "_" & temp
			
			if ((count of thetempday) as string) < 2 then set thetempday to "_" & thetempday as string
			set end of TallyString to thetempday & " : " & temp & " " & GraphString & return
		end if
	end repeat
	set the_content to my SetTheHeading() & ¬
		"For the previous month (Universal time), we processed..." & return & return & ¬
		"Total Mail items processed : " & MonthsTotal & return & return & ¬
		the TallyString & return & return & ¬
		"Have a good day."
	tell application "Mail"
		activate
		
		set newMessage to make new outgoing message with properties {address:the_mailto, subject:the_subject, content:the_content}
		tell newMessage
			set x to offset of TheBusinessName in the_content
			set font of characters x thru (x + (count of TheBusinessName)) of content to "Helvetica Bold"
			set color of characters x thru (x + (count of TheBusinessName)) of content to {56342, 2442, 607}
			make new to recipient with properties {address:the_mailto}
			send
		end tell
	end tell
end SendMonthlyReport

on SetTheHeading()
	return ("G'day" & return & return & "This is an automated message from " & TheBusinessName & "." & return & return)
end SetTheHeading

on SetDateTimeName(theEntireSeconds, WorkingDate)
	try
		set theDays to day of WorkingDate
		if theDays < 10 then set theDays to "0" & theDays
		set theHours to theEntireSeconds div 3600
		set theMinutes to (theEntireSeconds - (theHours * 3600)) div 60
		set theSeconds to theEntireSeconds - (theHours * 3600) - (theMinutes * 60)
		if theHours < 10 then set theHours to "0" & theHours as string
		if theMinutes < 10 then set theMinutes to "0" & theMinutes as string
		if theSeconds < 10 then set theSeconds to "0" & theSeconds as string
		copy the month of WorkingDate to tempMonth
		set StoreMonth to the month of WorkingDate as string
		
		copy ((offset of tempMonth in "jan feb mar apr may jun jul aug sep oct nov dec ") + 3) / 4 as integer to theMonth
		if theMonth < 10 then copy "0" & theMonth as string to theMonth
		
		set WorkingDateTimeName to (year of WorkingDate & "-" & theMonth & "-" & theDays as string) & " " & theHours & theMinutes & theSeconds & "Z.rtfd"
		return {theMonth, theDays, theHours, theMinutes, theSeconds, WorkingDateTimeName}
	end try
end SetDateTimeName

on CheckIfFileExists(temp_Folder, TheFileTempName, TheSuffix)
	tell application "Finder"
		try
			set FileSavingErrorMessage to ""
			set The_files to (every item of folder temp_Folder)
			set AddOnTime to 0
			set The_File_names to {}
			repeat with A_File in The_files
				set the end of The_File_names to A_File's name
			end repeat
			if TheFileTempName is in The_File_names then
				if TheSuffix ≠ "" then set TheFileTempName to my replace_chars(TheFileTempName, "." & TheSuffix, "")
				repeat
					set AddOnTime to AddOnTime + 1
					set xx to characters -5 thru -2 of TheFileTempName as string
					set xx to xx + AddOnTime as string
					if length of xx = 1 then set xx to "000" & xx as string
					if length of xx = 2 then set xx to "00" & xx as string
					if length of xx = 3 then set xx to "0" & xx as string
					set thetempname to characters 1 thru -6 of TheFileTempName & xx & "Z." & TheSuffix
					if thetempname is not in The_File_names then exit repeat
				end repeat
				set FileSavingErrorMessage to "There was an unusual file saving problem, probably due to the computers clock being reset." & return & "A file with the same name, '" & TheFileTempName & "' already existed." & return & "The file name is now set to '" & thetempname & "'." & return
			end if
		on error TheError number errNum
			display dialog errNum & return & "Error in CheckIfFileExists" & return & TheError as string
		end try
	end tell
end CheckIfFileExists

on CheckForExistingFileTwo(TheFileTempName, thetempname, append)
	try
		set RenameIsTrue to false
		tell application "Finder"
			try
				set templist to name of every item of folder holding_folder
				if thetempname is in templist or thetempname = templist then
					set thetempname to append & " " & TheFileTempName as string
					set append to append + 1
					set RenameIsTrue to true
					my CheckForExistingFileTwo(TheFileTempName, thetempname, append)
				else
					if exists item TheFileTempName of folder holding_folder then set the name of item TheFileTempName of folder holding_folder to thetempname
				end if
			on error TheError number errNum
				display dialog errNum & return & TheError
			end try
		end tell
		return RenameIsTrue
	end try
end CheckForExistingFileTwo

on CheckForExistingFileThree(TheFileTempName, thetempname, TheSuffix, append)
	tell application "Finder"
		try
			if TheSuffix ≠ "" then set TheFileTempName to my replace_chars(TheFileTempName, "." & TheSuffix, "")
			
			set templist to name of every item of folder "Unrecognized items for Manual printing"
			if (thetempname) is in templist or thetempname = templist then
				if TheSuffix ≠ "" then
					set thetempname to TheFileTempName & " " & append & "." & TheSuffix
				else
					set thetempname to TheFileTempName & " " & append
				end if
				set append to append + 1
				my CheckForExistingFileThree(TheFileTempName, thetempname, TheSuffix, append)
			else
				try
					if TheSuffix ≠ "" then
						if exists item (TheFileTempName & "." & TheSuffix) of folder holding_folder then
							set the name of item (TheFileTempName & "." & TheSuffix) of folder holding_folder to thetempname
						end if
					else
						if exists item (TheFileTempName) of folder holding_folder then
							set the name of item (TheFileTempName) of folder holding_folder to thetempname
						end if
					end if
				end try
				return thetempname
			end if
		on error TheError number errNum
			display dialog errNum & return & "CheckForExistingFileThree" & return & TheError as string
		end try
	end tell
end CheckForExistingFileThree

on seeifhourhaselapsed()
	set TheFileName to PathToDesktop & ".DataTimeSave.dat" as string
	set now to (current date)
	try
		set CheckLastTime to ((read file (TheFileName) as «class isot») as date)
		set TimeElapsed to now - CheckLastTime
	on error
		set TimeElapsed to hours + 1
	end try
	if (TimeElapsed > hours) then
		set fRef to (open for access file TheFileName with write permission)
		try
			set eof fRef to 0
			set now to now as «class isot»
			write now to fRef
			set now to (now as «class isot») as date
		end try
		close access fRef
		return true
	else
		return false
	end if
end seeifhourhaselapsed

on seeiftimehaselapsed(TheTest)
	set TheFileName to PathToDesktop & ".DataMinutesSave.dat" as string
	set now to (current date)
	try
		set TestContent to (read file (TheFileName))
		if TestContent ≠ "" then
			set CheckLastTime to ((read file (TheFileName) as «class isot») as date)
			set TimeElapsed to now - CheckLastTime
		end if
	on error
		set TimeElapsed to (60 * theMinutesToStop) + 1
	end try
	if TheTest = "Reset countdown" then
		set fRef to (open for access file TheFileName with write permission)
		try
			set eof fRef to 0
			set now to now as «class isot»
			write now to fRef
			set now to (now as «class isot») as date
			close access fRef
		end try
		return theMinutesToStop - TimeElapsed
	else
		if (TimeElapsed > 60 * theMinutesToStop) or TheTest = "Reset to empty" then
			set fRef to (open for access file TheFileName with write permission)
			try
				set eof fRef to 0
				set temp to ""
				write temp to fRef
				close access fRef
			end try
			return ""
		else
			if TheTest = "Check if elapsed" then
				if TestContent = "" then
					return ""
				else
					return (theMinutesToStop * 60) - TimeElapsed
				end if
			end if
		end if
	end if
end seeiftimehaselapsed

on SaveTheStartingReference(theItem)
	my SaveTheReference(".DataStartName.dat", theItem)
end SaveTheStartingReference

on SaveTheFinishedReference(theItem)
	my SaveTheReference(".DataFinishedName.dat", theItem)
end SaveTheFinishedReference

on SaveThePausedReference(theItem)
	my SaveTheReference(".DataPausedName.dat", theItem)
end SaveThePausedReference

on SaveTheReference(TheSaveFileList, theItem)
	set CheckPrintedList to my ReadFile(TheSaveFileList)
	if CheckPrintedList = {} then
		set end of CheckPrintedList to 1
	end if
	set ListLength to item 1 of CheckPrintedList
	if theItem is not in CheckPrintedList then
		if number of items in CheckPrintedList < 501 then
			set end of CheckPrintedList to theItem
			set ListLength to ListLength + 1
			set item 1 of CheckPrintedList to ListLength
			my WriteFile(TheSaveFileList, CheckPrintedList)
		else
			set ListLength to ListLength + 1
			if ListLength > 501 then set ListLength to 2
			set item 1 of CheckPrintedList to ListLength
			set item ListLength of CheckPrintedList to theItem
			my WriteFile(TheSaveFileList, CheckPrintedList)
		end if
	end if
end SaveTheReference

on CheckTheStartingReference(theItem)
	set TheSaveFileList to ".DataStartName.dat"
	set CheckPrintedList to my ReadFile(TheSaveFileList)
	if theItem is in CheckPrintedList then
		return true
	else
		return false
	end if
end CheckTheStartingReference

on CheckTheFinishedReference(theItem)
	set TheSaveFileList to ".DataFinishedName.dat"
	set CheckPrintedList to my ReadFile(TheSaveFileList)
	if theItem is in CheckPrintedList then
		return true
	else
		return false
	end if
end CheckTheFinishedReference

on CheckThePausedReference(theItem)
	set TheSaveFileList to ".DataPausedName.dat"
	set CheckPrintedList to my ReadFile(TheSaveFileList)
	if theItem is in CheckPrintedList then
		return true
	else
		return false
	end if
end CheckThePausedReference

on SaveAllTheData(TempSubject, FolderDailyName, TheYear)
	tell application "Finder"
		set The_Data_Desktop_Folder to "Mail Data " & TheYear
		if not (exists folder The_Data_Desktop_Folder of desktop) then
			make new folder at desktop with properties {name:The_Data_Desktop_Folder}
		end if
		set TheSaveFileList to The_Data_Desktop_Folder & ":" & FolderDailyName & ".dat"
		set CheckPrintedList to PrintDateTimeName & "," & theSendersFullName & "," & TempSubject
		my WriteFile3(TheSaveFileList, CheckPrintedList)
	end tell
end SaveAllTheData

on SetRunningTally(TheYear, theMonth, theDays)
	-- item 1 = Overall running total
	-- item 2 = yesterdays total
	-- item 3 = todays running total
	-- item 4 = the seconds
	set TheTally to my ReadFile(".RunningTally")
	if TheTally = {} then set TheTally to {0, 0, 0, 0}
	set FullTally to item 1 of TheTally
	set YesterdaysTally to item 2 of TheTally
	set PresentTally to item 3 of TheTally
	set theLastSeconds to item 4 of TheTally
	try
		set theGraphTally to items 5 thru 54 of TheTally
	on error
		set theGraphTally to {}
		repeat 50 times
			set end of theGraphTally to 0 as string
		end repeat
		set TheTally to items 1 thru 4 of TheTally & theGraphTally
	end try
	set item 1 of TheTally to FullTally + 1
	set item 3 of TheTally to PresentTally + 1
	set theLastMidnight to my ReadLastMidnight(".SaveLastMidnight")
	if theZeroedDate > theLastMidnight then
		my WriteLastMidnight(".SaveLastMidnight")
		my WriteYearlyData(TheYear, theDays, PresentTally)
		set item 2 of the TheTally to PresentTally
		set item 3 of TheTally to 1
		
		my SendABloodyTally(TheTally, theLastMidnight)
		set theGraphTally to {}
		repeat 50 times
			set end of theGraphTally to "0" as string
		end repeat
		set TheTally to items 1 thru 4 of TheTally & theGraphTally
	end if
	set thehour to theEntireSeconds div 3600 as text
	set item ((thehour * 2) + 5) of TheTally to thehour + 1 as string
	set item ((thehour * 2) + 6) of TheTally to (item ((thehour * 2) + 6) of TheTally) + 1
	set item 4 of TheTally to theEntireSeconds
	my WriteFile2(".RunningTally", TheTally)
end SetRunningTally

on ReadLastMidnight(Filename)
	tell application "Finder"
		set TheFileName to PathToDesktop & Filename as string
		try
			set theLastMidnight to (read file TheFileName as «class isot») as date
			return theLastMidnight
		on error
			my WriteLastMidnight(Filename)
			return theZeroedDate
		end try
	end tell
end ReadLastMidnight

on WriteLastMidnight(Filename)
	set TheFileName to PathToDesktop & Filename as string
	set fRef to (open for access file TheFileName with write permission)
	set theZeroedDate to theZeroedDate as «class isot»
	set eof fRef to 0
	try
		write theZeroedDate to fRef
	end try
	close access fRef
	set theZeroedDate to (theZeroedDate as «class isot») as date
end WriteLastMidnight

on ReadRunningTally()
	set TheTally to my ReadFile(".RunningTally")
	if TheTally = {} then set TheTally to {0, 0, 0, 0}
	return TheTally
end ReadRunningTally

on WriteYearlyData(TheYear, theDays, DaysTally)
	set theYearlyTallyName to ".Yearly Tally " & TheYear as string
	set YearlyTallyFile to PathToDesktop & theYearlyTallyName as string
	set yearlyTally to my ReadFile(theYearlyTallyName)
	if yearlyTally = {} or yearlyTally = "" then
		set TheWriteItem to {TheYear, StoreMonth, StoreMonth, theDays, DaysTally}
		set fRef to (open for access file YearlyTallyFile with write permission)
		set eof fRef to 0
		try
			repeat with x from 1 to number of items in TheWriteItem
				write (item x of TheWriteItem as string) & "," to fRef
			end repeat
			close access fRef
		on error
			try
				close access fRef
			end try
		end try
		-- Now check for previous years folder, should read December if full
		set tempyear to TheYear - 1
		set YearlyTallyFile2 to PathToDesktop & ".Yearly Tally " & tempyear as string
		try
			if exists file YearlyTallyFile2 then
				try
					set WholeList to (read file YearlyTallyFile2 using delimiter ",")
					set thecheckmonth to item 2 of WholeList
					my SendMonthlyReport(thecheckmonth, WholeList)
				end try
			end if
		end try
	else
		try
			set fRef to (open for access file YearlyTallyFile with write permission)
			write StoreMonth & "," & theDays & "," & DaysTally & "," as string to fRef starting at eof
			close access fRef
		on error
			try
				close access fRef
			end try
		end try
	end if
	tell application "Finder"
		try
			set WholeList to (read file (YearlyTallyFile) using delimiter ",")
			set thecheckmonth to item 2 of WholeList
			if thecheckmonth ≠ StoreMonth then
				set item 2 of WholeList to StoreMonth
				my WriteFile(theYearlyTallyName, WholeList)
				my SendMonthlyReport(thecheckmonth, WholeList)
			end if
		on error
			return {}
		end try
	end tell
end WriteYearlyData


on ReadFile(TheFileName)
	set TheFileName to PathToDesktop & TheFileName as string
	tell application "Finder"
		try
			set WholeList to (read file (TheFileName) using delimiter ",")
			return WholeList
		on error
			return {}
		end try
	end tell
end ReadFile

on WriteFile(TheFileName, TheWriteItem)
	set TheFileName to PathToDesktop & TheFileName as string
	set fRef to (open for access file TheFileName with write permission)
	set eof fRef to 0
	try
		write (item 1 of TheWriteItem as string) & "," to fRef
		repeat with x from 2 to number of items in TheWriteItem
			write item x of TheWriteItem & "," to fRef
		end repeat
	end try
	close access fRef
end WriteFile

on WriteFile2(TheFileName, TheWriteItem)
	set TheFileName to PathToDesktop & TheFileName as string
	set fRef to (open for access file TheFileName with write permission)
	set eof fRef to 0
	try
		repeat with x from 1 to number of items in TheWriteItem
			write (item x of TheWriteItem as string) & "," to fRef
		end repeat
	end try
	close access fRef
end WriteFile2

on WriteFile3(TheFileName, TheWriteItem)
	set TheFileName to PathToDesktop & TheFileName as string
	set fRef to (open for access file TheFileName with write permission)
	try
		write TheWriteItem & return to fRef starting at eof
	end try
	close access fRef
end WriteFile3

on WriteErrors(TheWriteItems, errNum)
	tell application "Finder"
		try
			set CheckErrorList to {}
			set TheSaveErrorsList to "Item Mover Errors.dat"
			set CheckErrorList to my ReadFile(TheSaveErrorsList)
			if (count of CheckErrorList) > 50 then set CheckErrorList to items ((count of CheckErrorList) - 49) thru end of CheckErrorList
			set end of CheckErrorList to (return & (current date) - (time to GMT) as string) & "  Error number : " & errNum & return & TheWriteItems
			my WriteFile(TheSaveErrorsList, CheckErrorList)
		on error TheError number errNum
			-- Do nuttin
		end try
	end tell
end WriteErrors

on replace_chars(this_text, search_string, replacement_string)
	set KeepDelimiters to AppleScript's text item delimiters
	set AppleScript's text item delimiters to the search_string
	set the item_list to every text item of this_text
	set AppleScript's text item delimiters to the replacement_string
	set this_text to the item_list as string
	set AppleScript's text item delimiters to KeepDelimiters
	return this_text
end replace_chars

on getName(TheFileTempName)
	set KeepDelimiters to AppleScript's text item delimiters
	set AppleScript's text item delimiters to {":"}
	if TheFileTempName > "" then
		set TheFileTempName to (text items -1 thru end of TheFileTempName)
	end if
	set AppleScript's text item delimiters to KeepDelimiters
	return TheFileTempName
end getName

on textToList(theText, theSep)
	set {myTID, my text item delimiters} to {my text item delimiters, theSep}
	set soFar to text items of theText
	set my text item delimiters to myTID
	return soFar
end textToList

on listToText(thelist, theSep)
	set {myTID, my text item delimiters} to {my text item delimiters, theSep}
	set soFar to thelist as Unicode text
	set my text item delimiters to myTID
	return soFar
end listToText

on quit
	continue quit
end quit


Model: intel iMac
Browser: Safari 525.18
Operating System: Mac OS X (10.5)

G’day

For your information.

I’ve worked out what the problem is.

After removing a message from a series of messages in a mailbox, using a repeat loop or any other way, after about 5-10 seconds the Mail App seems to send an update signal to itself, or to Applescript, I’m not sure which.

This update causes any dialog box, or open message, to very briefly ‘flicker’. Once that happens, the script can’t run anything else.

The workaround is to run the main script on it’s own, and call it from a short folder attached script.

The problem only arises when the script is directly attached as a folder action, and in Leopard.

A definite bug I think.

Regards

Santa

Model: intel iMac
Browser: Safari 525.18
Operating System: Mac OS X (10.5)