Refactored and solved bug