Fix some potential undefined or implementation-specified behavior and simplify code at the same time :)