This commit generally moves variable declarations to the smallest scope the variables are used in. This makes the code more readable by making it clearer when variables are used and by removing the block of variable declarations at the top of each function.