Declare main variables, make some variables local

- Declare some important variables at the top of the script
- Variables inside functions should all be local now