Refactoring -- Replaced repeated code with local functions