Add environment protection. Finishes #1598