Bug fix and optimisations