Fix some uses of undefined values and integer overflow. Closes ticket:4216
Merge branch 'bugfixes' into 3.1