Refactoring and bug fixes for 'generate_file' function