Cleaned up the script and have it writing to files