Fixed math and encoder functions

DO NOT revert any of these changes without discussion and explicit
agreement.