Refactored some of the code. Moved and defined global variables at the top.

reduced down some of the functions and broke some of them out to additional functions to lighten the work each one was doing and make it easier to follow.