refer to python reference implementation