Revamped version with precomputation