Refactor functions for more code reuse