restore original environment after purging + minor refactoring

This should now fix the bug reported in #692.

The minor refactoring in `modules.py` should have been part of #697, but was left out in error.