Move variables to the function scope in which they are needed

Somewhat a matter of style: variables should be scoped as closely to
where they are used as possible.
Add more comments