Refactor behavior into several functions for reusability