Various bugfixes

See my comments below per commit