refactor and added comments