Reduce variable scope when possible

Remove unused variables

Spotted by cppcheck
Made some functions const
Change some functions to static