Rewrite with C APIs
Cleanup and move functions into class to be testable