Improved readability. Also converted some code to use 'with'.