Implemented better way to create top-level environment.
Fixed some memory leaks.