Lots of fixes and changes

See commit history for more detail