some style changes, and use a try-finally black for opening files