Refactor and added comments