Refactored and modularized