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