Use "with" to wrap blocks instead of explicit open/close/try/finally

This makes the code cleaner in general, and prepares the ground for more OO refactoring of the code.