Fix accidental global variables

Ensure all variables in functions are indeed declared as local as intended.