Refactor file writing code into write_file method.

Also change the default directory and file name extension.