Various bugfixes and improvements