Hopefully fixes #109

Please someone have a look at this and test it.

I could only test it in a separate 'test'-script, which does the same, but is very simplified.

Is there more error handling with `fopen` and `fclose` needed?