Refactored the code and added documentation.