Refactored code still buggy