use AppleScript version "2.4" -- Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

property scriptName : name of me
property userName : short user name of (system info)

property cs : ""
property sn : ""
property EOL : "
"
if cs = "" then set cs to load script "/Users/" & userName & "/Desktop/Scripts/Script Libraries/Common2.scpt"
if sn = "" then set sn to load script "/Users/" & userName & "/Desktop/Scripts/Script Libraries/Swap SurNames.scpt"

property obituaryDirectory : "/Users/fwharris/Sites/obituaries/"

set theFiles to cs's glob(obituaryDirectory)

set theRenamesFiles to theFiles
set theRenamesFiles to cs's replacePattern("(?i)^(?!.*.txt).*", theRenamesFiles, "") -- remove non text files

set theRenamesFiles to cs's replacePattern("(?i)(\\ *obituary\\ *.txt|\\s*obit\\ *.txt)", theRenamesFiles, ".txt") -- remove obit

set theLastNameFiles to cs's findPattern("(?i)^[a-z\\-]*,.*", theRenamesFiles) -- 
set theRenamesFiles to cs's replacePattern("(?i)^[a-z\\-]*,.*", theRenamesFiles, "") -- remove files containing , after name at begin of line

set theRenamesFiles to cs's replacePattern("(?si)^(.*?)\\ ([a-z]+)\\ (\\b(?:sr|jr|IV|III|II|I)\\b)(.txt)", theRenamesFiles, "$1 $3 $2$4")

set theRenamesFiles to cs's replacePattern("(?i)(.*) (\\b[a-z\\']+\\b).txt", theRenamesFiles, "$2, $1.txt")

set cmd to "echo \"Asd!1fasdf\" | sudo -S ls -al " & quoted form of (obituaryDirectory)
set allFiles to do shell script cmd
repeat with i from 1 to count of theFiles
	if item i of theFiles ≠ item i of theRenamesFiles then
		set theSource to quoted form of (obituaryDirectory & item i of theFiles)
		set thedestination to quoted form of (obituaryDirectory & item i of theRenamesFiles)
		set cmd to "mv -v " & theSource & " " & thedestination
		try
			log (do shell script cmd)
		end try
	end if
end repeat

say "All done."