C code converted to python (untested)