Massive refactoring and memory optimisation