cleaned up code and added better logging