Reduce variable scope when possible

Remove unused variables

Spotted by cppcheck
Fix possible null pointer dereference.

Fixes CID 966176