Refactored, not tested