refactored functions to handle most cases