Refactored to reduce number of annonymous functions to make it easier to debug