Some more code ported from Go implementation