Refactoring for better code reuse and input handling