changed file handling to use context manager ; minor style changes

Asaf, you said I should just do the change myself, and you were right.
There's some stuff there that seems not functional yet(e.g. in some of the cases nothing was actually being written into the files) and I hope I didn't confuse anything .