Refactoring and cleanup
Improving file writing routines