Lots of random bugfixing