Bug fixes and optimisations. Fixes #20