Refactor code and add documentation