Bug fixes. Please see the commits for details.