Need Help! string manipulation?

I’m currently making a script to copy the contents of a file, append a new string at the end of the file, and write a new file. My problem now is that in the existing file, there is a bracket which is supposed to be at the end of the file. What should I do to append the new string to the file just before the bracket? I’m really stuck on this problem and I hope someone could help.

illustration:

this is how the source file looks like:

main {
var a
var b
var c
}

this is how the new file should look like after appending NEW STRING:

main {
var a
var b
var c
NEW STRING
}

this is how the ACTUAL OUTPUT file looks like after appending NEW STRING:

main {
var a
var b
var c
}
NEW STRING
}

notice the extra “}”

i’m using simple file handling (see code below)


	set theFile to (open for access (POSIX file unixPath))
	set theText to (read theFile for (get eof theFile))
	close access theFile

        set theFileContents to theText & "NEW STRING" & return & "}"
	set theFile to (open for access (POSIX file theFile) with write permission)
	write theFileContents to theFile as string
	close access theFile

The most simplest answer is

set sourceCode to "main { 
var a
var b
var c
}"
set codeToAdd to "var x"

set AppleScript's text item delimiters to string id 10 --or string id 13
set newCode to text items 1 thru -2 of sourceCode & codeToAdd & text item -1 of sourceCode as string
set AppleScript's text item delimiters to ""

return newCode

But I don’t like this approach. Probably it’s something from a programming/scriptinglanguage and I prefer to parse the source code just like a compiler/interpreter would do. In this case the accolades means that it is a list of commands separated with a return