Refactor; add comments and tests