refactored to get rid of some duplication