Loads of bugfixes

Tested most new features of previous commit.
See top of script for more details.