refactor and added comments: