Serious refactoring of the code