Refactor and fix math bugs.