Counting characters in file name, asking for new one if too long

I have a piece of a script that counts characters in a file name and asks the user to rename the file if it is over 25 characters long

The issue I have is that if the new name entered already exists for a file, the script gives an error and stops…I need help getting the script try to rename the file, but if the name given already exists it will ask for a new name

I figur this would be easy, but my brain doesn’t seem to work right now.

on setName(fileList)
tell application “Finder”
repeat with thisItem in fileList
set item_name to name of thisItem
set name_length to count item_name
if kind of thisItem is not “Folder” then
if name_length > 25 then
set answerOne to text returned of (display dialog �
“This file’s name has too many characters. It has " & name_length �
& " characters, but the limit is 25 total. Please enter a new name, or trim this name down.” buttons {“Proceed”} default button 1 default answer item_name)
set name of thisItem to answerOne
end if
end if
my setName(thisItem)
end repeat
end tell
end setName

I think this will do what you want:

property max_chars : 25

on setName(fileList)
	tell application "Finder"
		repeat with thisItem in fileList
			set item_name to name of thisItem
			set item_container to container of thisItem as string
			if kind of thisItem is not "Folder" then
				set name_length to count item_name
				if name_length > max_chars then
					set the_error to "This file's name has too many characters. It has " & name_length & " characters, but the limit is " & max_chars & " total. "
					repeat
						set item_name to text returned of (display dialog the_error & "Please enter a new name:" buttons {"Proceed"} default button 1 default answer item_name)
						set the_error to ""
						set name_length to count item_name
						if name_length > max_chars then
							set the_error to "This file's name has too many characters. It has " & name_length & " characters, but the limit is " & max_chars & " total. "
						else
							try
								get (item_container & item_name) as alias
								set the_error to "A file with the name " & item_name & " already exists. "
							end try
						end if
						if the_error = "" then exit repeat
					end repeat
					set name of thisItem to item_name
				end if
			end if
		end repeat
	end tell
end setName

Jon