Extract parsing the environment into a function

It was getting in the way of reading what the message handler did.