code cleanup and tiny optimisations