Removed duplication in math and refactoring.