refactoring and adding more handling for edge cases