Better error handling.

Also fixed two small bugs.