Write to file on the verge of working!

Fixed many more bugs. Writing to file still doesn't work though.
Currently writing to one file ends prematurely.