Reorganized and refactored code for ease of maintenance.