refactored and fixed