This code seriously needs to be tested and cleaned up, but it more or less does what it is supposed to.