Changed some global vars to local vars for best practices. Comments updated for clarity.