refactored, and added comments