refactored apply function, tests pass