Fix a couple of nil pointer errors

Backport some fixes from trunk.

Fixes:
https://bugs.launchpad.net/bugs/1357482
https://bugs.launchpad.net/bugs/1358585