refactored slightly