refactored and clarified the code a bit more