Test written + bugs squashed

I have written a test for setenv and I have squashed loads of bugs in the
process.