refactored somewhat