This became a bit of a mess as I ported it, and I just copied the generated code over, without the comments. So lets reorder all the functions to correspond to the C version and add all the comments back so that things remain clear