Applescript to Sync SmartGroups with iPhone

Since the iPhone does not sync SmartGroups from the MacOS Address Book (only regular groups), I wrote this script to automatically create ordinary groups with the contents of my SmartGroups.  I name all of my SmartGroups starting with “SM” and the script creates regular groups with the same name, but starting with “” (so SM_Family would become _Family).

Note that this script will delete all contacts from any regular groups that begin with “_” and match the name of a SmartGroup, so be a bit careful before you run it the first time.

on replaceString(theText, oldString, newString)
    set AppleScript's text item delimiters to oldString
    set tempList to every text item of theText
    set AppleScript's text item delimiters to newString
    set theText to the tempList as string
    set AppleScript's text item delimiters to ""
    return theText
end replaceString

tell application "Address Book"
    set theGroups to every group
end tell

repeat with aGroup in theGroups
    if id of aGroup contains "ABSmartGroup" then
        set theName to "_" & replaceString((name of aGroup), "SM_", "")

        tell application "Address Book"
            if group theName exists then
                remove every person from group theName
                make new group with properties {name:theName}
            end if
            add (every person in aGroup) to group theName
        end tell
    end if
end repeat

tell application "Address Book" to save addressbook