added various optimisations and fixes