Reorganised IO to be clearer with the "with" statement and changed when file closing happens so as to reduce file lock as much as possible

There might be indentation errors, I'm not used to using tabs and I had to change my editor settings a few times