passes all tests
Works, needs optimization
Modification for profiling