Cleaned up code and added better error handling