Refactored and reorganized code