Reduced the scope of a bunch of variables and removed unused variables.