reorganized code for the C api