and fixing output files

TODO: extract all file writing to function