Various improvements to code ported from C