Some bugfixes and improvements

See the commits for more information.