Added write_to_file function and some checks.