Soundex routine for Applescript

I came across the PLEAC web site at and found a soundex routine in Python. After a little bit, I was able to rework it for AppleScript. (Soundex converts a surname into a string used by genealogists and motor vehicles administrations. Sound-alike surnames should have similar soundex codes. Smith, for example would be S530, as would Smyth and Schmidt)

-- altered from original at

on upper(input) -- input is a list
	repeat with n from 1 to (count of items of input)
		if (ASCII number (item n of input)) > 96 then
			set item n of input to (ASCII character ((ASCII number (item n of input)) - 32))
		end if
	end repeat
	return input
end upper

on removeDupes(input) -- input is a list
	-- set inputList to characters of input as list
	set inputLen to count of items of input
	set n to 1
		if n < inputLen then
			if (item n of input) = (item (n + 1) of input) then
				repeat with x from (n + 1) to (inputLen - 1)
					set item x of input to item (x + 1) of input
				end repeat
				set inputLen to inputLen - 1
				set n to n + 1
			end if
			exit repeat
		end if
	end repeat
	return (items 1 through inputLen of input)
end removeDupes

on soundex(nameStr)
	(* soundex module conforming to Knuth's algorithm
        implementation 2000-12-24 by Gregory Jorgensen
        public domain
	-- digits holds the soundex values for the alphabet
	set digits to "01230120022455012623010202"
	set sndx to {}
	set fc to ""
	-- translate alpha chars in name to soundex digits
	set nameX to characters of nameStr
	set fc to item 1 of nameX
	set nameX to upper(nameX)
	set nameX to removeDupes(nameX)
	set digitList to characters of digits -- If I weren't too lazy, digits wouldn't exist
	repeat with n from 2 to count of items of nameX
		set c to item n of nameX
		set d to (ASCII number c) - 64
		if item d of digitList ≠ "0" then
			set sndx to sndx & item d of digitList
		end if
	end repeat
	if ((count of items of sndx) = 2) then
		set sndx to sndx & "0"
	else if ((count of items of sndx) = 1) then
		set sndx to sndx & "0" & "0"
	end if
	return fc & (items 1 thru 3 of sndx as string)
end soundex

set dialogResult to display dialog "Enter a surname:" default answer ""

set surname to text returned of dialogResult

set theCode to soundex(surname)

display dialog theCode