Cleaned up code and refractored