refactored, added comments, added better logging