optimisations and bug fixing