refactor and add comments