Improved #ifdef placement, and error handling.
Merge branch 'master' into issue-22