Apply some optimizations suggested by David Lyons.