fix for #381 squashed and cleaned.

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