Cleaned up the code a bit, will document later.