avoiding dividing by zero and a little refactoring