refactor and clean up code

- Add comments.
- Update the code to reduce code replication.