Fix warnings, improve comments and error handling, minor refactoring (#656)

Authored by snowleopard on Aug 22 2018, 6:49 PM.