refactored for cleaner code and fewer function calls