C code based on work done with a python version.