cleaned up a bit, added comments and fixed a few small bugs on the way