refactored (partially)