Refactor and document code