More refactoring and optimisation