refactored into smaller functions and added docstrings