Generate function now writes to stdout or, optionally, a file