Lots of bugfixes

This script is so damn broken. It's a little less broken now.