property prefsDomain : "com.fcs.applescript.saveTerminalDirectories"

on run
	set r to display alert "Modify Terminal directories" message "What action do you want?" buttons {"Save", "Restore"}
	if (button returned of r is "Save") then
		saveTerminalDirectories()
	else
		repeat with dir in getDirectoriesFromCache()
			tell application "Terminal"
				do script "cd " & dir
			end tell
		end repeat
	end if
end run

on getDirectoriesFromCache()
	try
		tell application "System Events"
			set p to POSIX path of preferences folder
			set p to p & "/" & prefsDomain & ".plist"
			display dialog p
			set f to property list file p
			return value of contents of f
		end tell
	on error
		return {}
	end try
end getDirectoriesFromCache

on saveTerminalDirectories()
	tell application "System Events"
		set tmp to POSIX path of temporary items folder
		set tmp to tmp & "/term_script.txt"
	end tell
	set dirs to {}
	tell application "Terminal"
		set wins to every window
		repeat with win in wins
			if not win is busy then
				do script "pwd > " & tmp in win
				set dir to do shell script "cat " & tmp
				set dirs to dirs & {dir}
			end if
		end repeat
	end tell
	do shell script "rm " & tmp
	writeToPreferences(dirs)
end saveTerminalDirectories

on writeToPreferences(dirs)
	tell application "System Events"
		set out to POSIX path of preferences folder
		set out to out & "/" & prefsDomain
		set f to my createPropertyListFileAtPath(out)
		set value of contents of f to dirs
	end tell
end writeToPreferences

on createPropertyListFileAtPath(p)
	if p ends with ".plist" then
		set p to (characters 1 thru ((length of p) - (length of ".plist")) of p) as string
	end if
	set q to ""
	if p contains " " then
		repeat with c in p
			if c contains " " then
				set q to q & "\\"
			end if
			set q to q & c
		end repeat
	else
		set q to p
	end if
	do shell script "defaults write " & q & " key value"
	set p to p & ".plist"
	tell application "System Events"
		return property list file p
	end tell
end createPropertyListFileAtPath