Major refactoring of functions