Cleanup the main function

I made the main function slightly more general and safer (encapsulate open inside a with)