Refactored slightly to allow testing