Refactored script to be testable and reusable