Refactored and simplified code