optimized version that appears in 1405.3272