updated function to print to a file if filename is provided in arguments