Refactor code; add comments