refactoring, fixing corner cases