Refactored code to be more readable and more modular. Most functionality relocated to fuctions.