Refactored for modularity and testing