refactored and improved