global replaceKeys
global replaceValues

tell application "Pages"
	tell the front document
		set replaceKeys to {%@}
		set replaceValues to {%@}
		set paraCount to 1
		repeat with para in paragraphs of body text
			set fieldString to ""
			if para contains "<$" then
				set fieldString to para as string
				set x to 1
				repeat with key in replaceKeys
					set replaceValue to item x in replaceValues
					set the fieldString to my replace_chars(fieldString, key, replaceValue)
					set x to x + 1
				end repeat
				set paragraph paraCount of body text to fieldString
			end if
			set paraCount to paraCount + 1
		end repeat
		
		my searchAndReplaceInTables(tables)
		my searchAndReplaceInTextItems(text items)
		my searchAndReplaceInShapes(shapes)
		
		repeat with aGroup in my flattenedGroups(groups)
			my searchAndReplaceInTables((tables of aGroup))
			my searchAndReplaceInShapes((shapes of aGroup))
			my searchAndReplaceInTextItems((text items of aGroup))
		end repeat

		save
	end tell
end tell

on searchAndReplaceInTables(someTables)
	tell application "Pages"
		repeat with aTable in someTables
			tell aTable
				repeat with aCell in cells
					set fieldString to value of aCell as text
					set newString to fieldString
					set tokensFoundInCell to {}
					if fieldString contains "<$" then
						(*We found an occurance*)
						set y to length of fieldString
						set x to 1
						repeat until x is y
							set tokenString to ""
							set nextCharacter to x + 1
							if character x of fieldString contains "<" and character nextCharacter of fieldString contains "$" then
								(*We found the start*)
								repeat until character x of fieldString contains "$" and character nextCharacter of fieldString contains ">"
									set tokenString to tokenString & character x of fieldString
									set x to x + 1
									set nextCharacter to x + 1
								end repeat
								set tokenString to tokenString & "$>"
								copy tokenString to end of tokensFoundInCell
							end if
							set x to x + 1
						end repeat
					end if
					
					if (count of tokensFoundInCell) is greater than 0 then
						set rIndex to 1
						repeat with key in replaceKeys
							set replaceValue to item rIndex in replaceValues
							set the newString to my replace_chars(newString, key, replaceValue)
							set rIndex to rIndex + 1
						end repeat
						if length of newString > 0 then
							("Setting text value to cell")
							set value of aCell to newString as text
						end if
					end if
					
				end repeat
			end tell
		end repeat
	end tell
end searchAndReplaceInTables

on searchAndReplaceInShapes(someShapes)
	repeat with aShape in someShapes
		my searchAndReplaceTokenStrings(aShape)
	end repeat
end searchAndReplaceInShapes

on searchAndReplaceInTextItems(someTextItems)
	repeat with aTextItem in someTextItems
		my searchAndReplaceTokenStrings(aTextItem)
	end repeat
end searchAndReplaceInTextItems

on flattenedGroups(someGroups)
	local groupList
	set groupList to {}
	tell application "Pages"
		repeat with aGroup in someGroups
			if (count of aGroup) > 0 then
				repeat with bGroup in my flattenedGroups((groups in aGroup))
					copy bGroup to the end of groupList
				end repeat
			end if
			copy aGroup to the end of groupList
		end repeat
		
	end tell
	return groupList
end flattenedGroups

on searchAndReplaceTokenStrings(obj)
	tell application "Pages"
		tell the front document
			repeat with i from 1 to the count of obj
				set aItem to item i of obj
				tell aItem
					set fieldString to object text as text
					set newString to fieldString
					set tokensFound to {}
					if fieldString contains "<$" then
						(*We found an occurance*)
						set y to length of fieldString
						set x to 1
						repeat until x is y
							set tokenString to ""
							set nextCharacter to x + 1
							if character x of fieldString contains "<" and character nextCharacter of fieldString contains "$" then
								(*We found the start*)
								repeat until character x of fieldString contains "$" and character nextCharacter of fieldString contains ">"
									set tokenString to tokenString & character x of fieldString
									set x to x + 1
									set nextCharacter to x + 1
								end repeat
								copy tokenString to end of tokensFound
							end if
							set x to x + 1
						end repeat
					end if
					if (count of tokensFound) is greater than 0 then
						set rIndex to 1
						repeat with key in replaceKeys
							set replaceValue to item rIndex in replaceValues
							set the newString to my replace_chars(newString, key, replaceValue)
							set rIndex to rIndex + 1
						end repeat
					end if
					
					if length of newString > 0 then
						set object text to newString
					end if
				end tell
			end repeat
		end tell
	end tell
	return tokensFound
end searchAndReplaceTokenStrings

on replace_chars(this_text, search_string, replacement_string)
	set AppleScript's text item delimiters to the search_string
	set the item_list to every text item of this_text
	set AppleScript's text item delimiters to the replacement_string
	set this_text to the item_list as string
	set AppleScript's text item delimiters to ""
    (*we delay the next replacement to avoid missed replacements when there are multiple occurrences of the same merge key in batch merge*)
    delay 0.001
	return this_text
end replace_chars
