Fix potential overflow and dividing by zero