Fix edge case, minor refactoring