Fix some uses of undefined values and integer overflow. Closes ticket:4216