ported from threex/