Many different bug fixes

Please see invididual commits for a list of bug fixes.