Numerous fixes and minor optimisations