Optimizations courtesy of John Dethridge