Add some helper functions from the C++ version and clean up code.