Cleaned up code readability, optimized frequently run code and improved error handling