Rewrite moments.

To resolve the bug of the previous version we rewrote the code.