Various bug fixes.

closes #176
Merge branch 'origin/master'