more refactoring and added docstring