--define globals
global completeMailboxList --list of all mailboxes to be imported or processed
global MacOSVersion --string for determining whether to system is Mac OS X or not
global pathToMailFolder --string for full path to Mail folder on Mac OS X
global pathToDesktop --string for path to Desktop folder on boot volume
global theOriginalMbox --mbox raw contents with ASCII 13 line endings
global theFinalMbox --mbox raw contents with ASCII 10 line endings
global importFolderName --string for name of import folder on Desktop
global importFolderLocation --string containing path to import folder on Desktop
global tempMboxFile --string for path to pre-processed mbox file
global mboxName --string for name of current mbox being processed
global mboxFile --string for path for post-processed mbox file
global pathToMailbox --string for path to mailbox in hierarchy
global emailClient --string for name of email client

--define variables
set completeMailboxList to {}
set AppleScript's text item delimiters to ""

--determine the version of Mac OS that is running
try
	get path to extensions
	set MacOSVersion to "Mac OS"
	tell application "Finder" to set pathToDesktop to ((desktop) as string)
on error
	display dialog "This script will only run when you have started up in Mac OS 9.x or earlier. Please use the Mac OS X scripts instead." buttons {"Quit"} default button 1
	return
end try

--set some defaults based on client name
set emailClient to "Outlook Express"
set importFolderName to "Outlook-Import"

tell application "Outlook Express"
	my WaitUntilReady()
	set savedSchedules to {}
	set allSchedules to every «class cSch»
	set numberOfSchedules to length of allSchedules
	repeat with eachSchedule in allSchedules
		set savedSchedules to savedSchedules & «class enbl» of eachSchedule
		set «class enbl» of eachSchedule to false
	end repeat
	set topLevelfolderList to every «class cFld»
	repeat with eachFolder in topLevelfolderList
		my traverseOutlookFolders(eachFolder)
	end repeat
	my createImportFolderOnDesktop()
	my displayOpeningDialog(emailClient)
	repeat with eachMailbox in completeMailboxList
		set mailboxIsFolder to 0
		set mailboxHasMessages to 0
		my findPositionOfOutlookMailboxInHierarchy(eachMailbox)
		try
			if (number of items in every «class cFld» of eachMailbox) is greater than 0 then
				set mailboxIsFolder to 1
			end if
		end try
		try
			if (number of every «class msg » in eachMailbox) is greater than 0 then
				set mailboxHasMessages to 1
			end if
		end try
		my createMailboxInImportFolder(eachMailbox, mailboxIsFolder, mailboxHasMessages)
		if (mailboxHasMessages is equal to 1) then
			tell application "Finder" to set theOriginalMbox to (open for access file mboxFile with write permission)
			set messageList to every «class msg » of eachMailbox
			set totalMessageCount to length of messageList
			repeat with counter from 1 to totalMessageCount
				set currentMessage to «class msg » counter of eachMailbox
				my writeToLog(("Importing message " & counter as string) & ": " & «class subj» of currentMessage)
				set messageHeader to "From " & «class addr» of «class sndr» of currentMessage & " " & «class tims» of currentMessage
				set messageContent to messageHeader & return & «class mSrc» of currentMessage
				set AppleScript's text item delimiters to return
				set intervalCounter to 0
				try
					repeat
						set startCounter to (intervalCounter * 1000) + 1
						set endCounter to (intervalCounter * 1000) + 1000
						try
							set subContent to text items startCounter thru endCounter of messageContent
						on error
							set subContent to text items startCounter thru -1 of messageContent
						end try
						set AppleScript's text item delimiters to ASCII character 10
						tell application "Finder" to write (subContent as string) & (ASCII character 10) to theOriginalMbox starting at eof
						set AppleScript's text item delimiters to return
						set intervalCounter to intervalCounter + 1
					end repeat
				end try
			end repeat
			tell application "Finder" to close access theOriginalMbox
		end if
	end repeat
	set allSchedules to every «class cSch»
	repeat with counter from 1 to numberOfSchedules
		set «class enbl» of «class cSch» counter to item counter of savedSchedules
	end repeat
	quit
end tell
my moveMailToFinalDestination()

--routines

on convertASCII()
	set theOriginalMbox to (open for access file tempMboxFile)
	set theFinalMbox to (open for access file mboxFile with write permission)
	try
		repeat
			set eachLine to (read theOriginalMbox before return)
			write eachLine & (ASCII character 10) to theFinalMbox starting at eof
		end repeat
	end try
	try
		close access theOriginalMbox
		delay 1
	end try
	try
		close access theFinalMbox
		delay 1
	end try
	tell application "Finder" to delete alias tempMboxFile
end convertASCII

on createImportFolderOnDesktop()
	set safeImportFolderName to my makeUniqueName(importFolderName, pathToDesktop)
	set importFolderName to safeImportFolderName
	tell application "Finder"
		make new folder at alias pathToDesktop with properties {name:importFolderName}
		activate
		open alias (pathToDesktop & importFolderName)
	end tell
end createImportFolderOnDesktop

on createMailboxInImportFolder(localMailbox, localMailboxIsFolder, localMailboxHasMessages)
	tell application "Finder"
		my displayStartingImportDialog(name of localMailbox as string)
		if (localMailboxIsFolder is equal to 1) then
			set pathToNewFolder to pathToDesktop & importFolderName & ":" & pathToMailbox
			set nameOfLocalMailbox to name of localMailbox
			make new folder at alias pathToNewFolder with properties {name:nameOfLocalMailbox}
			if (localMailboxHasMessages is equal to 1) then
				set mboxName to "•" & name of localMailbox & ".mbox"
			end if
			set importFolderLocation to pathToNewFolder & nameOfLocalMailbox & ":"
		else
			set mboxName to name of localMailbox & ".mbox"
			set importFolderLocation to pathToDesktop & importFolderName & ":" & pathToMailbox
		end if
		if (localMailboxHasMessages is equal to 1) then
			set safeMboxName to my makeUniqueName(mboxName, importFolderLocation)
			set mboxName to safeMboxName
			set tempMboxFile to importFolderLocation & mboxName & ":mboxTemp"
			set mboxFile to importFolderLocation & mboxName & ":mbox"
			make new folder at alias importFolderLocation with properties {name:mboxName}
		end if
	end tell
end createMailboxInImportFolder

on displayOpeningDialog(applicationName)
	activate
	set displayString to applicationName & " is ready to go..."
	display dialog displayString buttons {"Continue"} default button 1 giving up after 10
	writeToLog(displayString)
end displayOpeningDialog

on displayStartingImportDialog(localNameOfMailbox)
	activate
	set displayString to "Starting import of mailbox '" & localNameOfMailbox & "'..."
	display dialog ("Starting import of mailbox '" & localNameOfMailbox & "'..." & return & return & ¬
		"[This dialog will be dismissed in 3 seconds]") buttons {"•"} default button 1 giving up after 3
	writeToLog(return & displayString)
end displayStartingImportDialog

on findPositionOfOutlookMailboxInHierarchy(currentMailboxID)
	tell application "Outlook Express"
		set pathToMailbox to ""
		set parentMailboxes to {}
		set success to 0
		set currentMailbox to name of currentMailboxID
		set currentParent to (name of parent of currentMailboxID)
		set currentParentID to currentMailboxID
		repeat until success is equal to 1
			if (currentParent is equal to "Outlook Express") then
				set success to 1
			else
				set parentMailboxes to parentMailboxes & currentParent as list
				set currentParentID to (parent of currentParentID)
				set currentParent to (name of parent of currentParentID)
			end if
		end repeat
	end tell
	set lengthOfPathToMailbox to length of parentMailboxes
	if (lengthOfPathToMailbox is greater than 0) then
		set reversedList to reverse of parentMailboxes
		repeat with counter from 1 to lengthOfPathToMailbox
			set pathToMailbox to pathToMailbox & item counter of reversedList & ":"
		end repeat
	end if
end findPositionOfOutlookMailboxInHierarchy

on makeUniqueName(proposedFile, proposedLocation)
	set AppleScript's text item delimiters to ""
	tell application "Finder"
		set mboxExtension to 0
		set dotPosition to (offset of ".mbox" in proposedFile) as number
		if (dotPosition is not equal to 0) then
			set mboxExtension to 1
			set namePrefix to ((characters 1 thru (dotPosition - 1) of proposedFile) as string)
		end if
		set success to 0
		set counter to 1
		set proposedName to proposedFile
		repeat until success is equal to 1
			set allNames to {}
			try
				set allNames to allNames & name of every file of alias proposedLocation
			end try
			try
				set allNames to allNames & name of every folder of alias proposedLocation
			end try
			if (allNames) contains proposedName then
				if (mboxExtension is equal to 1) then
					set proposedName to (namePrefix & " " & counter as string) & ".mbox"
				else
					set proposedName to proposedFile & " " & counter as string
				end if
				set counter to counter + 1
			else
				set success to 1
				return proposedName
			end if
		end repeat
	end tell
end makeUniqueName

on moveMailToFinalDestination()
	if MacOSVersion is equal to "Mac OS X" then
		tell application "Finder"
			set success to 0
			set counter to 1
			set originalFile to alias (pathToDesktop & importFolderName)
			set currentName to importFolderName
			repeat until success is equal to 1
				if name of every folder of alias pathToMailFolder contains currentName then
					set currentName to importFolderName & " " & counter as string
					set name of originalFile to currentName
					set originalFile to alias (pathToDesktop & currentName)
					set counter to counter + 1
				else
					set originalFile to pathToDesktop & currentName
					move alias originalFile to pathToMailFolder
					set success to 1
				end if
			end repeat
		end tell
		activate
		display dialog "Importing done! If Mail is already running, you need to quit and relaunch Mail." buttons {"OK"} default button 1
	else if MacOSVersion is equal to "Mac OS" then
		activate
		display dialog "Importing done! A folder was created on your Desktop called '" & importFolderName & ¬
			"' which contains your exported email from " & emailClient & ". " & return & return & "Follow the instructions in the Read Me file to move this folder to the proper location on your Mac OS X  machine." buttons {"OK"} default button 1
	end if
end moveMailToFinalDestination

on traverseOutlookFolders(currentFolder)
	tell application "Outlook Express"
		set completeMailboxList to completeMailboxList & (currentFolder as list)
		set subFolders to every «class cFld» of currentFolder
		repeat with eachFolder in subFolders
			my traverseOutlookFolders(eachFolder)
		end repeat
	end tell
end traverseOutlookFolders

on WaitUntilReady()
	with timeout of 5 seconds
		repeat
			try
				tell application "Outlook Express" to get version
				return
			on error number errNum
			end try
		end repeat
	end timeout
end WaitUntilReady

on writeToLog(passedString)
	set pathToLogfile to pathToDesktop & importFolderName & ":log"
	set theData to (open for access file pathToLogfile with write permission)
	write (passedString & return) to theData starting at eof
	close access theData
end writeToLog