Code optimisations and cleanup