reference impl, untested.