many fixes and optimisations