Refactored logic, seems to work now