refactored and somewhat functional