Fix variable referenced before assignment bug

Because += is an assignment statement, using it on a variable masks any
variable of the same name in an outer scope. This means if the variable
does not have a value set in the inner scope it is seen as read before
being written to.

This works around the issue by pulling the increment outside of the
nested function where it was being performed into the main function.