Refactoring/streamline env detection

Various cleanups and globals removal.