Improved scope checking to include functions