Copy/pasted in most of my original script, but it is now only partially tested.