port of the C code