Fixes for #317, #339, #365.