Cleanup and provide more efficient agorithms for some helper functions.