refactored and working correctly