refactored to 185 lines