Bug fixes and optimisations. Seems to be working.