Refactor mathimpl a bit and add docstrings