lei's rewrite for speeding up computation