Optimisations and code refactoring