added math functions and cleaned up code