Multiple bugfixes

Lots of bugfixes and general tidying up.
For beta release.