moved some things around, found a bug in the algorithm