Refactor the code and add comments