refactored and tested