ターミナルを現在のフォルダで開く、その2

http://d.hatena.ne.jp/ytqwerty/20090510#p2では、Terminal.appが起動していないときにウィンドウが2つ開かれてしまう…‥起動時にデフォルトでウィンドウ開く動作を抑制する方法が無さそうだった…‥ので、起動していないときは、起動時に開くウィンドウに対してコマンドを送りつけることにしました。

tell application "System Events"
	set terminal_launched to exists (application processes whose bundle identifier is "com.apple.Terminal")
end tell

tell application "Finder"
	if Finder window 1 exists then
		try
			set select_item to selection as alias
			set folder_selected to (select_item as string) ends with ":"
		on error
			set folder_selected to false
		end try
		if folder_selected then
			-- when Folder selected
			set target_path to POSIX path of select_item
		else
			-- when Folder opened
			set target_folder to target of Finder window 1
			set target_path to POSIX path of (target_folder as alias)
		end if
		set cmd to "cd " & (quoted form of (target_path as text))
		tell application "Terminal"
			if terminal_launched then
				do script cmd
			else
				-- wait for window opened
				repeat
					set n to count window
					if n > 0 then
						exit repeat
					end if
					delay 0.1
				end repeat
				-- find window
				set new_window to window 1
				-- execute
				do script cmd in new_window
			end if
			activate
		end tell
	else
		-- when no Finder window
		tell application "Terminal"
			if terminal_launched then
				do script ""
			end if
			activate
		end tell
	end if
end tell