refactored and fixed bug