Refactor and add comments