refactored and cleaned up