Reduce variables scope, move declaration to first use point

This reduces variables scope for more readable code and also moves one declaration to the initialization point. No behavior is changes.

Too wide scope part was identified using Cppcheck.