Add environment handling. Fix some bugs.