Move variable declarations to more specific scopes

These variables were declared in the main scope of a function, but are only used in a specific block. Moving them there makes the code cleaner and avoids cppcheck warnings.