Add protection against division by zero.
Remove unneeded index computation.