fix for #381 squashed and cleaned.

Resubmitting the PR for #381 with squashed commits and cleaned up code. See #404 for details.