Switched the unlocking of scopes to defer unlocking until the function ends.