Scripting in cash receipts

Hi all,

I have done some scripting before where I write in lines to things like Sales order and Purchase order but have not ever tried cash receipts and it looks like it is a bit different based on what I am seeing! I am hoping someone here might have some advice on the strange behavior I am seeing with the script posted below. The script is supposed to recognize when line balance is between -4 and 4 dollars, insert a line with a GL distribution for the opposite of the line balance, then go back to the first line and change the amt posted to match the invoice. It is performing all the calculations correctly but when I accept the script (I have tried both Pre-Write and Post-Write on the Header) it seems to mess with the invoice total and amount posted for that line. I feel like this is likely related to having to recalculate posting amounts or something? But I am just not sure where to go from here. Any help would be appreciated!

DepNo = ""
DivNo = ""
CustNo = ""
DepType = ""
AmtPosted = 0
Balance = 0
Bal = 0
TotBal = 0
NewAmt = 0
RevBal = 0

retVal = oBusObj.GetValue("DepositNo$", DepNo)
retVal = oBusObj.GetValue("ARDivisionNo$", DivNo)
retVal = oBusObj.GetValue("CustomerNo$", CustNo)
retVal = oBusObj.GetValue("DepositType$", DepType)

Set oLines = oBusObj.AsObject(oBusObj.Lines)

retVal = oLines.MoveFirst()
Do Until CBool(oLines.EOF) = True

retVal = oLines.GetValue("AmountPosted", AmtPosted)
retVal = oLines.GetValue("InvoiceBalance", Balance)

if Balance >-4 and Balance <4 then
Bal = Balance
TotBal = Bal + TotBal
End If

retVal = oLines.MoveNext()
Loop

if TotBal <> 0 then
RevBal = TotBal *-1
End If

if RevBal <> 0 then
retVal = oLines.AddLine()
retVal = oLines.SetValue("DepositNo$",DepNo)
retVal = oLines.SetValue("ARDivisionNo$", DivNo)
retVal = oLines.SetValue("CustomerNo$",CustNo)
retVal = oLines.SetValue("DepositType$", DepType)
retVal = oLines.SetValue("LineType$","G")
retVal = oLines.SetValue("AccountKey$", "100-00-00")
retVal = oLines.SetValue("AmountPosted", RevBal)
retVal = oLines.Write()
End If

retVal = oLines.MoveFirst()
Do Until CBool(oLines.EOF) = True

if Balance >-4 and Balance <4 then
NewAmt = AmtPosted + Balance
retVal = oLines.SetValue("AmountPosted", NewAmt)
End If

retVal = oLines.MoveNext()
Loop