refactor code and add comments