Some bugfixes and opimisations