Updates and improvements from Jonas Koelker. [originally from svn r7601]