Changed implementation to use a more functional approach