Algo optimisation and refactoring