Various bug fixes

I'll rebase after #262. Done.