Refactored math code.