Refactoring + minor optimisations