major refactoring of the c code