various refactorings and optimisations