Major refactoring of code