Several fixes and improvements.

Fixes #514 and #515