A bunch of optimisations and fixes.