Fix heap overflow vulnability. Be more careful about integer overflow.
While here: fix possible divide-by-zero.
Notified by: feld@ MFH: 2015Q3