Find and Change Hyperlink

I automated creation of a mail message using Applescript, but I need to find and change a hyperlink as part of that automation process. I have written some code, which I would like to use as a sub-routine, but I am having some trouble getting it to work properly. I would appreciate some assistance. Here is what I have written:

use framework “Foundation”
use framework “AppKit”
use scripting additions

set _theURL to getvariable “theURL”
tell application id “com.apple.mail” – Mail
set _String to (current application’s selection
set start to (_String’s |length|()) - 1
repeat
set {_URL to (_String’s attribute:(current application’s NSLinkAttributeName) atIndex:start effectiveRange
if _URL is not “” then
set linkText to _theURL
end if
set start to (location of theRange) - 1
if start < 0 then exit repeat
end repeat
end tell

Thanx…